2016-08-07 189 views
1

我創建了一個名爲Boot的類,在這裏面我改變了文件的路徑,所以用戶可以調用它來設置自定義路徑,如下所示:無法訪問更改的屬性

class Boot 
{ 
    private static $_filePath = 'directory/'; 

    public function __construct() 
    { 
     require 'system.php'; 
    } 

    public function init() 
    { 
     new System(); 
    } 

    public function setFilePath($newDir) 
    { 
     $this->_filePath = $newDir; 
    } 

    public static function getFilePath() 
    { 
     return self::_filePath; 
    } 
} 

所以在我index.php文件:

require 'boot.php'; 

$b = new Boot(); 
$b->setFilePath('directories/'); 
$b->init(); 
系統類

現在我把這樣的事情:

echo Boot::getFilePath(); 

並應顯示directories/但我再次看到默認值:directory

現在我雖然認爲這個問題涉及到static這個字段,但是我怎樣才能訪問到更改後的值呢?謝謝。

回答

1

定義有和沒有static的類變量是不同的變量。

一種解決方案是從變量的聲明刪除static,改變getPath代碼,因爲你已經擁有的Boot實例定義WITN new

class Boot 
{ 
    private $_filePath = 'directory/'; 

    public function __construct() 
    { 
     require 'system.php'; 
    } 

    public function init() 
    { 
     new System(); 
    } 

    public function setFilePath($newDir) 
    { 
     $this->_filePath = $newDir; 
    } 

    public function getFilePath() 
    { 
     return $this->_filePath; 
    } 
} 

並調用getFilePath()作爲

echo $b->getFilePath(); 

另一種解決方案是同時更改setFilePathgetFilePath

public function setFilePath($newDir) 
{ 
    // set STATIC variable 
    self::$_filePath = $newDir; 
} 

public static function getFilePath() 
{ 
    // get STATIC variable 
    return self::$_filePath; 
} 

但最後這是一個壞的方法,因爲您會犯錯誤決定您是否需要訪問static variableproperty of an object

所以最好做出一個決定 - 要麼你有一個Boot的實例並獲取它的屬性,或者你只有一個類中的靜態方法而忘記了Boot實例。

+0

nope,我在'System'中沒有'Boot'的任何實例。我在'index.php'文件中有'Boot'的實例,但是我需要從'boot'中聲明的類'system'中訪問'boot'內'$ _filePath'的路徑。我不知道現在是否更清楚。 –

+0

將'$ b'作爲參數傳遞給'System'構造函數。 –

+0

這是解決問題的唯一解決方案嗎? –