1

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);
2
  • 3
    Well, yes, this definitely wouldn't work. Strings are not objects.... Commented May 9, 2012 at 19:36
  • Or you could set up an array of objects (with the strings as keys) and loop through it. Commented May 9, 2012 at 19:37

1 Answer 1

2

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()

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

3 Comments

class gets initialized before attempt
He won't need to instantiate the object if it is a static method.
$this->$$mapperName->fetchAll($options);

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.