简体   繁体   中英

How to access the instance of the main class from an anonymous in PHP 7?

I'm trying to access the instance of the class where it contains an anonymous as we do in Java, eg:

JAVA

class MyClass 
{
    private String prop = "test";

    public void test()
    {
        new Runnable() {

            public void run() 
            {
                // I can access MyClass.this from here
                System.out.println(MyClass.this.prop);
            }

        }.run();
    }
}

PHP 7

<?php

class MyClass
{
    private $prop = "test";

    public function test()
    {
        $class = new class{

            public function run() 
            {
                // ???? MyClass::$prop ????
            }

        };
    }
}

How can I access the MyClass instance from within the anonymous?

Use this:

class MyClass
{
    public $prop = "test";

    public function test()
    {
        $class = new class($this){
            private $parentObj;
            public function __construct($parentObj)
            {
                $this->parentObj = $parentObj;
            }
            public function run() 
            {
                echo $this->parentObj->prop;
            }
        };
        $class->run();
    }
}

$x = new MyClass();
$x->test();

The key is to inject $this as a constructor parameter of the anonymous class.

Note: I've changed your private $prop to public so i wouldn't have to write a getter for it ;)

See if here: https://3v4l.org/IRhXd

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM