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

时间:2016-11-01 12:02:00

标签: php oop variables

我有一个非常简单的课程:

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

我想在'someFunction'里面定义一个'on the fly'变量,但我似乎无法弄清楚如何在函数范围内这样做。

$classInstance = new MyClass();

$varName = 'dynamicVariable';
$classInstance->$varName;

我想做什么:

$classInstance = new MyClass();

$varName = 'dynamicVariable';
$classInstance->functionScopeReference->$varName;


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

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

2 个答案:

答案 0 :(得分:4)

答案 1 :(得分:1)

通过使用$this keyword ...我会建议一个关于面向对象编程的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();