dynamic object creation by string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MartijnHoekstra
    New Member
    • Sep 2010
    • 39

    dynamic object creation by string

    Hi,

    Is there a way to instantiate an object by string?

    The current project I am working on is to create a set of php files, each containing a class derived(extende d) from 1 particular base class.
    Each PHP's filename contains the name of the class it embeds. (e.g. "ClassABC.p hp" contains "class ABC extends")

    With string manipulation I am able to extract the text "ABC" from the filename.
    Now I'd like to build an array of base class type and instantiate ABC as one of the elements on that array.

    So how could I do that having the string "ABC"?
  • Canabeez
    New Member
    • Jul 2009
    • 126

    #2
    Here, try this, hope it helps.

    Good luck.

    [code="php"]
    <?php
    class newClass{
    public $hello;

    public function __construct(){
    $this->hello = "Hello World!";
    }
    }


    $className = 'newClass';

    eval("\$cls = new {$className};") ;

    var_dump( $cls->hello );
    ?>[/code]

    Comment

    • Markus
      Recognized Expert Expert
      • Jun 2007
      • 6092

      #3
      Code:
      class x{}
      $class = 'x';
      $inst = new $class;
      No eval needed.

      Comment

      • Canabeez
        New Member
        • Jul 2009
        • 126

        #4
        Thank's for the "V", but i believe Markus's answer is better :)

        Comment

        Working...