在函数内部设置类变量的值,并在下次调用该类时访问它

时间:2018-11-03 13:51:30

标签: php class phalcon

我正在类中设置类变量。 现在,我编写了一个使用变量的方法。我写的代码就是这样

class someController extends someBase{
private $var;
var_dump($var); //line 3

public function someFunc(){
$this->var = null
$this->var = $this->otherFunction(); //assume this returns string "Barack Obama"
      }
}

第一次访问控制器时,第3行的值为null。 如何编写代码,以便下次访问该控制器时,第3行的var_dump输出为“ Barack Obama”。

我已经研究了getter和setter,但是由于我是php的新手,所以我无法完全了解它的工作原理。

1 个答案:

答案 0 :(得分:0)

<?php
class someBase{

}
class someController extends someBase{
private $var = null;
private  $count = 0;
//var_dump($var);  you can't print anything directly from class itself, you must print it inside function.

    public function someFunc(){
        $this->count++;
        if($this->count == 1)
            var_dump($this->var); // null value can't be printed by echo or print as there is no value assigned to null value. in order to print null value you should print it as string
        else
            echo $this->var = $this->setter_function(); 
    }
    private function setter_function(){
        return "Barack Obama";
    }
}


$obj = new someController();
$obj->someFunc();
$obj->someFunc();



?>