Rawb
Rawb

Reputation: 33

referencing class variable by a string

This is some pseudo code represents my code which you wouldn't inderstand scope.

Class Tester has private vars, hold classes. Array holds the base name of var. Function bar attempts to contruct the variable in string from, then use it. If this can't be done I understand, but i'm just constructing a variable name.

Class Tester{

     private $preClass1post = new TestClass1();

     private $preClass2post = new TestClass2();;

     private $preClass2post = new TestClass2();;

     public $classBasicNames = array('Class1','Class2','Class3');

     function Bar(){
          foreach($classBasicNames as $classBasicName){

             $fullClassName = 'PreText'.classBasicName.'PostText';

             $fullClassName->DoWork();
             //always throws object does not exist
          }

}

}


                    //actual code for context
            $mapperName = 'mapper'.$entityName.'Stat';
            echo $mapperName;
            $dbos = $this->{$mapperName}->fetchAll($options);

Upvotes: 1

Views: 97

Answers (1)

petr
petr

Reputation: 2586

First of all, you seem to be calling methods on objects - even if you evaluate the string to get the class, you still need to instantiate the object.

You can do:

$class = 'PreText'.classBasicName.'PostText';
$object = new $class();
$object->DoWork();

See example 3 here, or visit related discussion.

Update:

If a variable name is known, use $$fullClassName->doWork()

Upvotes: 2

Related Questions