tags:

views:

144

answers:

3

Hi, i have a class of this kind

Class Car {
private $color;

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

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

}

Then i create some instances of it:

$blue_car  = new car('blue');

$green_car = new car('green');

etc.

Now i need to call method get_color() on the fly, according to instance's name

$instance_name='green_car';

Is there any way to do it?

A: 
$green_car->get_color()

will be equivalent to

call_user_func(array($$instance_name, 'get_color'))
jimyi
+4  A: 
$$instance_name->get_color();
${$instance_name}->get_color();

or something of the like.

Edit:

Tested...

<?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

?>

Both worth in php 5.2

Josh
Thanks, that's what i need.
Ursus Russus
Why don't you accept the answer?
blockhead
Fell asleep, sorry.
Ursus Russus
A: 

I'm not sure why need to call the instance "by name", usually you just pass the instance as a parameter or assign it to another variable. By default, PHP5 will just make another reference to the class, not copy it. But you can use =& for good measure and make it obvious what you are doing.

$blue_car = new Car('blue');
$red_car = new Car('red');

$current_car =& $blue_car
$current_car->get_color();  // returns blue car's color

$current_car =& $red_car
$current_car->get_color();  // returns red car's color
Brent Baisley