2016-08-07 188 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

这是解决问题的唯一解决方案吗? –