AlexWerz
AlexWerz

Reputation: 739

Instantiating a PHP class using a variable is not working

This is working:

$x = new classname();

This is not working:

$class = "classname";
$x = new $class();

The error I get is "Class classname not found". PHP version is 5.4.22. Any ideas? As far as I have researched into this topic this is exactly what you need to do in order to instantiate a class using a variable.

My actual testcode (copy+paste), $build = 1:

//include the update file
$class="db_update_" . str_pad($build, 4, '0', STR_PAD_LEFT);
require_once(__ROOT__ . "/dbupdates/" . $class . ".php");

$x = new db_update_0001();
$xyz="db_update_0001";
$x = new $xyz();

The class definition:

namespace dbupdates;

require_once("db_update.php");

class db_update_0001 extends db_update
{
...
}

I just found out that my editor added

use dbupdates\db_update_0001;

to the file. So that explains why "new db_update_0001();" is working. What i want to achieve is that I dynamically include database updates which are stored in files like dbupdates/db_update_0001.php

Regards, Alex

Upvotes: 1

Views: 1168

Answers (2)

TiMESPLiNTER
TiMESPLiNTER

Reputation: 5889

You have to use the full qualified class name. Which is namespace\classname. So in your case the code should be:

$x = new db_update_0001();
$xyz="dbupdates\db_update_0001";
$x = new $xyz();

The use statement is useless if you like to instantiate a class by using a variable as classname.

Upvotes: 5

Vaugen Wakeling
Vaugen Wakeling

Reputation: 81

Try this

<?php
$className = yourClassName();
$x = new $className;
?>

Upvotes: -2

Related Questions