1

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?

1
  • Of course - otherwise than obvious (and slow) way through eval(); Commented Mar 29, 2010 at 0:00

3 Answers 3

5
$$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

Sign up to request clarification or add additional context in comments.

Comments

0
$green_car->get_color()

will be equivalent to

call_user_func(array($$instance_name, 'get_color'))

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.