[英]how can I use of a class property in the nested function
Why a class property is not accessible in the nested function ? 为什么在嵌套函数中无法访问类属性? So how do I use it?
那么我该如何使用呢?
class MyClass
{
public $var = "I'm a class property!";
public function Test()
{
function SubTest()
{
// I need to $this->var; here
}
}
}
I want to echo
$var
in the SubTest()
. 我想在
SubTest()
echo
$var
。 Is it possible ? 可能吗 ?
What about doing this? 怎么办呢?
<?php
class MyClass{
public $var = "I'm a class property!";
public function Test(){
function SubTest(&$father){
$father->var = 'something else';
echo 'here ! '.$father->var.'<br />';
}
echo $this->var.'<br />';
SubTest($this);
echo $this->var.'<br />';
}
}
$test = new MyClass();
echo $test->var.'<br />';
$test->Test();
?>
Gives this result: 给出以下结果:
I'm a class property!
I'm a class property!
here ! something else
something else
How about using a closure? 使用闭包怎么样?
$this
is visible inside the closure since PHP 5.4. 自PHP 5.4起,
$this
在闭包内部可见。
And besides that you should not be defining a function inside a method like this. 除此之外,您不应该在这样的方法内定义函数。 PHP functions are global, means they behave in exactly the same way as if they had been declared outside.
PHP函数是全局函数,这意味着它们的行为与在外部声明时完全相同。
class MyClass
{
public $var = "I'm a class property!";
public function Test($str)
{
$callback = function() use ($str)
{
print_r($this->var . " " . $str);
};
return call_user_func($callback);
}
}
$a = new MyClass();
$a->Test("My name is not Foo.");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.