Mr. Bug Mr. Bug - 4 months ago 7
PHP Question

Cannot access to changed property

I've created a class called

Boot
, inside this I've a method that change the path of a file, so the user can call it to set a custom path, something like this:

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;
}
}


so in my
index.php
file:

require 'boot.php';

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


Now in the system class I call something like this:

echo Boot::getFilePath();


and should be displayed
directories/
but I see again the default value:
directory
.

Now I though that this issue is related to the
static
field, but how can I access to the changed value so? Thanks.

Answer

Class variables defined with and without static are different variables.

One solution is to remove static from variable declaration and change getPath code, as you already have instance of Boot defined 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;
    }
}

And call getFilePath() as

echo $b->getFilePath();

Another solution is to change both setFilePath and getFilePath:

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

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

But in the end it's a bad approach because you will make mistakes deciding whether you need to access a static variable or a property of an object.

So it's better to make a decision - either you have an instance of Boot and get properties of it or you have only static methods in a class and forget about Boot instance.