Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, new variable class in namespace

I'm experimenting with PHP 5.3's namespacing functionality and I just can't figure out how to instantiate a new class with namespace prefixing.

This currently works fine:

<?php
new $className($args);
?>

But how I can prepend my namespace in front of a variable classname? The following example doesn't work.

<?php
new My\Namespace\$className($args);
?>

This example yields: Parse error: syntax error, unexpected T_VARIABLE

like image 327
Jfdev Avatar asked Oct 29 '11 02:10

Jfdev


People also ask

What does :: class do in PHP?

SomeClass::class will return the fully qualified name of SomeClass including the namespace. This feature was implemented in PHP 5.5. It's very useful for 2 reasons. You can use the use keyword to resolve your class and you don't need to write the full class name.

How namespace works in PHP?

Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task. They allow the same name to be used for more than one class.

Does PHP have namespace?

In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.

What is fully qualified class name PHP?

Fully qualified name. This is an identifier with a namespace separator that begins with a namespace separator, such as \Foo\Bar . The namespace \Foo is also a fully qualified name. Relative name. This is an identifier starting with namespace , such as namespace\Foo\Bar .


2 Answers

Try this:

$class = "My\Namespace\\$className";
new $class();

There must be two backslashes \\ before the variable $className to escape it

like image 93
JRL Avatar answered Oct 21 '22 22:10

JRL


Here's how I did it:

$classPath = sprintf('My\Namespace\%s', $className);
$class = new $classPath;

Note the single quotes instead of double.

like image 36
mehov Avatar answered Oct 21 '22 22:10

mehov