Lee Loftiss
Lee Loftiss

Reputation: 3195

Loading PHP classes from string

I'm looking for a way to load classes into PHP without using hardwired names.

The idea is the script will load a text file with names of 'components'(classes), then load them by the names in the file. For example:

<xml><Classes><class name="myClass"/></Classes></xml>

When the PHP is run, it would need to do something like this:

require_once {myClass}".class.php";
var myclass = new {myClass}();

Upvotes: 8

Views: 12750

Answers (4)

gravi
gravi

Reputation: 77

Why not just use autoloader

spl_autoload_register(function ($class) {
    require 'class_folder/' . $class . '.class.php';
});

Upvotes: 0

Samuel Corradi
Samuel Corradi

Reputation: 49

Use the ReflectionClass for this.

require_once $class . ".class.php";

$refl = new \ReflectionClass($class);

$params_for_construct = array($param1, param2);

$instance = $refl->newInstanceArgs($params_for_construct);

Upvotes: 0

Brad Turner
Brad Turner

Reputation: 458

Your example is almost correct as is. You can just replace {myClass} with $myClass and it should work.

Here's a simple example of how this could be used:

File: myClass.class.php

<?php
    class myClass {
        public $myVar = 'myText';
    }
?>

File: test.php

<?php
    $className = "myClass";
    require_once $className . ".class.php";
    $myInstance = new $className;
    echo $myInstance->myVar;
?>

This should output "myText" to the screen, the contents of your dynamically included class property.

Upvotes: 3

deceze
deceze

Reputation: 522091

require_once $class . ".class.php";
$myclass = new $class;

See http://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.new.

Upvotes: 6

Related Questions