将受保护函数中的变量传递给php中同一类中的公共函数


passing variables from a protected function to a public function inside the same class in php

我有一个类,里面有两个函数,如下所示:

class MyClassName
{
    protected function myFunction1()
    {
        // some code here
        return $something;
    }
    public function myFunction2()
    {
        // some code here
        return $somethingElse;
    }
}

我需要做的是在myFunction1()中定义一个变量,然后在myFunction2()中使用它。做到这一点的最佳做法是什么?

class MyClassName
{
    public $var = 0;
    protected function myFunction1()
    {
        // some code here
        $this->var = ...;
        return $something;
    }
    public function myFunction2()
    {
        // some code here
        echo $this->var;
        return $somethingElse;
    }
}

实际上应该在函数外定义vars,然后设置一个值。然后可以通过这样做对所有脚本进行修改->var

将其作为类属性

class MyClassName
{
    private $property;
    public function __construct() {
        $this->myFunction1();
    }
    protected function myFunction1()
    {
        // some code here
        $this->property = 'an apple';
    }
    public function myFunction2()
    {
        // some code here
        return $this->property;
    }
}

现在测试一下:

$my_class = new MyClassName();
$something = $my_class->myFunction2();
echo $something;