douhuai2015 2011-07-02 05:56
浏览 46
已采纳

如何通过PHP类中的任何方法设置变量的值?

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 function __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();

  • 写回答

1条回答 默认 最新

  • dongqing7789 2011-07-02 06:06
    关注

    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
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳