开发者

how can i set the value of a variable be accessed by any method in a PHP Class?

I'm trying to use 2 methods in my class.

the class structure looks something similar to this

class Test extends Something
{
    private $dir;

    public func开发者_C百科tion __construct()
    {
        parent::__construct();
    }

    private function check_theme()
    {
        // do some checking here
        $this->dir = // outcome of the checking
    }

    public function load_theme()
    {
        $this->check_theme();
    }

    public function load_file()
    {
        $this->dir . $path . $to . $file
    }
}

ok so now, this only works if I run something like

$test = new Test();

$test->load_theme();
$test->load_file();

but now I have a different method that I want to access directly but I really want for that method to already know what the value of $dir is.

so if I used $test->load_file(); It would load the file because the value of $dir was already set by $test->check_theme();


I hope I get your question properly. I suggest to keep a flag for when the value of $dir is set.

Here before using the $dir value, we do the test to ensure its value is set. If not we call $load_theme() which calls check_theme() just in the same sequence as you showed in your question.

class Test extends Something
{
    private $dir;
    private $file_loaded;

    public function __construct()
    {
        parent::__construct();
        $this->file_loaded = false;

    }

    private function check_theme()
    {
        // do some checking here
        $this->dir = // outcome of the checking
    }

    public function load_theme()
    {
        $this->check_theme();
        $this->file_loaded = true;   
    }

    public function load_file()
    {
        if (!$this->file_loaded)
            $this->load_theme();            
        $this->dir . $path . $to . $file
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜