PHP类:按实例名称调用类实例中的方法

Urs*_*sus 1 php oop

我有一类这样的课

Class Car {
private $color;

public function __construct($color){
$this->color=$color;
}

public function get_color(){
return $this->$color;
}

}
Run Code Online (Sandbox Code Playgroud)

然后我创建它的一些实例:

$blue_car  = new car('blue');

$green_car = new car('green');

etc.
Run Code Online (Sandbox Code Playgroud)

现在我需要根据实例的名称动态调用方法get_color()

$instance_name='green_car';
Run Code Online (Sandbox Code Playgroud)

有什么办法吗?

Jos*_*osh 5

$$instance_name->get_color();
${$instance_name}->get_color();
Run Code Online (Sandbox Code Playgroud)

或类似的东西.

编辑:

经测试...

<?php
class test_class{
    public function __construct( $value ){
        $this->value = $value;    
    }
    public function getValue(){
        return $this->value;
    } 
}

$test = new test_class( "test" );
$test2 = new test_class( "test2" );

$iname = "test";
$iname2 = "test2";

echo $$iname->getValue(), "\r\n";    \\ echos test
echo ${$iname2}->getValue(), "\r\n"; \\ echos test2

?>
Run Code Online (Sandbox Code Playgroud)

两者都值得在PHP 5.2