如何从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