Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare class in namespace from string [duplicate]

Tags:

php

Possible Duplicate:
PHP namespace with Dynamic class name

How to declare class from string?

code

$name = 'the_class';
require_once $name.'.php';
$class = new \resource\$name();

error

Parse error: syntax error, unexpected '$name' (T_VARIABLE), expecting identifier (T_STRING)
like image 477
clarkk Avatar asked Oct 27 '25 10:10

clarkk


2 Answers

You will need to dynamically construct the namespace path:

$classPath = '\\resource\\' . $name;
$class = new $classPath;

Note: I like to be explicit with literal backslashes.

like image 126
Jason McCreary Avatar answered Oct 28 '25 23:10

Jason McCreary


The namespace needs to be part of the string:

$name = 'the_class';
require_once $name . '.php';
$className = '\resource\\' . $name;
$class = new $className();
like image 34
FtDRbwLXw6 Avatar answered Oct 29 '25 00:10

FtDRbwLXw6