在函数范围内定义动态变量


Defining dynamic variable inside function scope

我有一个非常简单的类:

 class MyClass
 {
      public function someFunction()
      {
         echo array_key_exists( 'dynamicVariable', $GLOBALS ) ? 'true' : 'false';
      }
 } 

我想在'someFunction'内部定义一个'动态'变量,但我似乎不知道如何在函数范围内做到这一点。

$classInstance = new MyClass();
$varName = 'dynamicVariable';
$classInstance->$varName;

我想做什么:

$classInstance = new MyClass();
$varName = 'dynamicVariable';
$classInstance->functionScopeReference->$varName;

$classInstance->myFunction(); <-- this will print TRUE

如何做同样的事情,但在someFunction范围内定义它,而不是MyClass范围?由于

作为社区wiki发布,以满足OP,因为dbf没有发布评论来关闭问题。

"简短的回答,你不能从方法范围之外,除非变量是在任何方法内部使用的属性。——dbf"

"@dbf谢谢!你可以发布这个评论作为答案,我将其标记为"0x29a"

使用$this关键字…我建议你上一门好的面向对象编程101课程,它应该比我能更好地解释作用域……

    class MyClass
{
    public function someFunction($foo)
    {
        $this->dynamicVariable = $foo;
    }
}
$classInstance = new MyClass();
$classInstance->someFunction('dynamicVariable');
echo $classInstance->dynamicVariable;

编辑:为了更好地回答OP的问题(抱歉没有正确阅读!):虽然它不改变作用域,但解决方法是使用getter和setter并使您的属性私有:

class MyClass
{
    private $property_one; // can't access this without using the getPropertyOne function
    private $property_two;
    public function setPropertyOne($bool)
    {
        $this->property_one = $bool;
    }
    public function getPropertyOne()
    {
        return $this->property_one;
    }
    public function setPropertyTwo($bool)
    {
        $this->property_two = $bool;
    }
    public function getPropertyTwo()
    {
        return $this->property_two;
    }
}
$classInstance = new MyClass();
// trying to access the properties without using the functions results in an error
echo $classInstance->property_one;
$classInstance->setPropertyOne(true);
echo $classInstance->getPropertyOne();
$classInstance->setPropertyTwo(false);
echo $classInstance->getPropertyTwo();