简体   繁体   English

如何在嵌套函数中使用类属性

[英]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.

相关问题 方法定义:如何使用类属性作为默认函数参数? - Method definition: how can I use class property as a default function parameter? 为嵌套类(社交链接)指定UL属性,但仍作为父类(标头)的属性工作,我该如何解决呢? - specifiy UL properties for nested class (sociallinks) but still it is working as a property of parent class (header) how can i solve it? 如何在控制器的 function 中设置 class 属性,并在另一个 function 中使用它? - How to set a class property in a controller's function and and use it in the other function? 如何访问此嵌套数组中的对象属性? - How can I access object property within this nested array? 我怎样才能将函数转换为类? - How can I call function into function into class? 当我使用addComplexType函数时,如何定义嵌套数组结构? - how to define nested array structure, when I use addComplexType function? 如何使用在PHP中作为类成员存储的回调函数? - How can I use a callback function which is stored as a class member in PHP? CodeIgniter:如何在库中使用安全类的xss_clean函数? - CodeIgniter: How can I use xss_clean function of security class inside a library? 如何使用类元数据? - How can I use class metadata? 如何在不使用全局变量的情况下在函数内使用 PHP 类方法? - How can I use PHP Class Method inside a function without using global variable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM