2015-02-23 47 views
0

我面臨一個問題,我想讓類頁面知道變量'$格式'。獲取類知道一個變量

// class1.php 
<?php 

    include('./class2.php'); 
    echo $format->getTest(); // returns :-) (declared in class2.php) 

    class Page { 

    PUBLIC function getText() { 
     return $format->getTest(); // returns Call to a member function getTest() on null 
    } 

    } 

    $page = new Page; 

?> 
// class2.php 
<?php 

    class Format { 

    PUBLIC function getTest() { 
     return ":-)"; 
    } 

} 

$format = new Format; 

?> 

任何建議/想法?

編輯:

我找到了一種方法:return $GLOBALS['format']->getTest(); 但我不喜歡它,它的這麼多的類型。任何其他方式?

菲利普

+0

['$頁=新頁($格式);'](HTTP: //php.net/manual/en/la nguage.oop5.dep.php) – PeeHaa 2015-02-23 18:59:08

+0

這是如何使''格式'已知'頁面? 反正,我得到更多的類不僅僅是'格式',有沒有使用構造函數的另一種方式?我的意思是,我已經在'class1.php'中獲得了varibale,還有什麼方法可以進入'class Page'中? – Philip 2015-02-23 19:01:15

回答

0

正確目標的解決方案是通過變量來構造函數,設置器或作爲參數getText()方法。選一個你認爲最適合你的案例。

構造

class Page 
{ 
    private $format; 

    public function __construct(Format $format) 
    { 
     $this->format = $format; 
    } 

    public function getText() 
    { 
     return $this->format->getTest(); 
    } 

} 

$page = new Page($format); 
echo $page->getText(); 

設置器

class Page 
{ 
    private $format; 

    public function setFormat(Format $format) 
    { 
     $this->format = $format; 
    } 

    public function getText() 
    { 
     return $this->format->getTest(); 
    } 

} 

$page = new Page; 
$page->setFormat($format); 
echo $page->getText(); 

參數

class Page 
{ 

    public function getText(Format $format) 
    { 
     return $format->getTest(); 
    } 

} 

$page = new Page; 
echo $page->getText($format); 
+0

謝謝!你對這個解決方案有什麼看法,我聲明一個構造函數,遍歷'$ GLOBALS'並聲明一個varibale,其中包含$ GLOBALS'包含的所有內容? – Philip 2015-02-23 19:28:23

+0

那麼如果你想硬編碼一切,那麼使用目標代碼有什麼意義呢?無論您做什麼,您都將擁有始終以相同方式工作的類(因爲它始終讀取全局變量)。這顯然不是你想要的,因爲(我認爲)將來會有新的格式,你會希望用另一種格式替換一種格式。 – 2015-02-23 19:35:14

+0

不,格式是我在文件夾'/ classes'中獲得的許多類中的一個類。我想通過使其可見,實現我需要的每個課程 – Philip 2015-02-23 19:36:59