Can I use a string variable to initialize a class in PHP? - php

I'd like to use a string variable to initialize an object. Is something like this possible?
$class = "MyClass";
$x = new $class();
return $x;
Edit: Ha, so when I tried to test this and it didn't work I had a syntax error somewhere else in my script. Apparently this works just fine. Neat.

Yes. Its possible in PHP.
$className = 'MyClass';
$object = new $className;
Attaching PHP documentation snippet on new operator

Related

How can I use a variable as the name of object's method?

Here is my code:
$method_name = 'mymethod()';
$obj = new Myclass();
$obj->$method_name;
As you see I've used $method_name as the name of a method. But it throws this error message:
Undefined property: app\classes\Myclass::$mymethod()
How can I fix it?
You should avoid using string to do reflection... And use the ReflectionClass and the ReflectionMethod.
However, the proper way of doing it is:
$method_name = 'mymethod';
$obj = new Myclass();
$obj->$method_name();
You have to use callback function call_user_func. To do this You need to make an array:
The 1st element is the object
2nd is the method
call_user_func(array($player, 'doIt'));
You can also do it without call_user_func:
$player->{'SayHi'}();
Or:
$method = 'doIt';
$player->$method();
You set method name to be mymethod(), that is invalid.
Set it just to mymethod:
$method_name = 'mymethod';
$obj = new Myclass();
$obj->{$method_name}();

Use variable as namespace

In some other file (someusername\classes\MyClass for instance), I have
<?php
namespace someusername;
class MyClass
{
static function Test()
{
echo "working";
}
}
?>
I have stumbled across an annoying little barrier:
<?php
$user = "someusername";
$class = "MyClass";
require_once "$user\\classes\\$class";
//This line should be the equivalent of 'use someusername as User;'
use $user as User; //Parse Error: syntax error, unexpected '$user'
$c = "User\\$class";
$UserSpecificClass = new $c();
?>
I can get around it via the following, but the use statement would make things a lot nicer
<?php
$user = "someusername";
$class = "MyClass";
require_once "$user\\classes\\$class";
$c = "$user\\$class";
$UserSpecificClass = new $c();
?>
Is it possible to use variables in use statement in PHP? Or is it better to avoid the use statement with this approach?
Importing is performed at compile-time.
Assigning the variable is done at run-time after compilation, at which point any import should already be imported.
So this is not possible. Best solution would indeed be to use the FQN in a string and initialize that.
$c = "$user\\$class";
$UserSpecificClass = new $c();

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
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.
Try this
<?php
$className = yourClassName();
$x = new $className;
?>

PHP get class reference of an object

for instance
I've a class called Ent, and have an object $ent
how can I get the class Ent out of $ent?
$ent = new Ent()
get_class(new Ent())
this will even work in earlier versions of PHP
You can use get_class($ent)
get_class - Returns the name of the class of an object
Reference php docs
You could get get_class().
Watch out though, if your calling it on a variable that might not be an object it will throw a warning.
if(is_object($ent))
{
$class = get_class($ent);
}
Ref: http://php.net/manual/en/function.get-class.php
$ent = new Ent();
$my_class = get_class($ent);
$new_ent = new $my_class;
RTM: Here

Instantiating class by string

i have this code.
$contrl = stripslashes($this->params['controller'].'Controller'); //PostController
$obj = new $contrl(); // What's won't work
//this don't work too
$contrl = 'PostController';
$obj = new $contrl();
//but this work good
$obj = new PostController();
I dont understand why it happen and how I can fix it?
I haven't tested it, but I'm pretty sure it should be done like this (as per the doc):
$obj = new $contrl;

Categories