When I call a class name in the parameters, I got error ‘Uncaught Error: Class "AdminController" not found’;
But when call it directly, everything is OK!
My classes in the same folder and in the same namespace "namespace Base;"
Array
(
[0] => D:WebwwwMyincludesAdminController.php
[1] => D:WebwwwMyincludesAdminModel.php
[2] => D:WebwwwMyincludesAdminView.php
[3] => D:WebwwwMyincludesBase.php
[4] => D:WebwwwMyincludesRouter.php
[5] => D:WebwwwMyincludesSiteController.php
[6] => D:WebwwwMyincludesSiteModel.php
[7] => D:WebwwwMyincludesSiteView.php
)
And on AdminController.php
:
namespace Base;
class AdminController{function index(){
}
}
The error:
namespace Base;
class Router
{
function loadClass($class){
require_once "$class.php";
$class="AdminController";
$obj = new $class(); <== This make Error
$obj = new AdminController(); <== This is has no error
}
}
3
Answers
that might be due to you are not looking at absolute way
normally classes only look at it’s containing folder or sub folders, and we needed to use os class’ methods to reach absolute way
for example:
car_sales = pd.read_csv(absulute_way)
When you call a class dynamically this way (e.g., with $class = "AdminController"; followed by new $class();), PHP looks it in the global namespace.
There are two ways of dynamically calling it-
Specify Hardcode Namespace "BaseAdminController" so PHP knows exactly which namespace to look in.
$class = "Base\AdminController"; $obj = new $class(); // Now it knows the full path!
You can use NAMESPACE if you want to dynamically load any class within the same namespace
$class = __NAMESPACE__ . "\" . $class; $obj = new $class();
However, when you use new AdminController(); directly, PHP understands that it’s in the same namespace (Base) as your current code.
Direct Instantiation Works: When you use new AdminController()
directly, PHP understands that AdminController refers to the class
within the current namespace (Base) because of the namespace
declaration at the top of the file.
Dynamic Instantiation Requires Fully Qualified Namespace: When you
assign $class = "AdminController" and then use new $class(), PHP
does not automatically assume that AdminController is in the Base
namespace. It will look for AdminController in the global namespace
unless you explicitly specify the namespace.