[英]PHP: How to return an instantiated class object, given a class name?
They say that eval() is evil . 他们说eval()是邪恶的 。 I want to avoid the use of the eval() line using proper PHP5 functionality.
我想避免使用适当的PHP5功能使用eval()行。 Given a class name in a static class method, how do I make it return a real object?
给定静态类方法中的类名,如何使其返回真实对象?
class Model {
public static function loadModel($sModelPath) {
if (!(strpos(' ' . $sModelPath, '/')>0)) {
$sModelPath .= '/' . $sModelPath;
}
$sModelName = str_replace('/','_',$sModelPath);
// P is a global var for physical path of the website
require_once(P . '_models/' . $sModelPath . '.php');
eval("\$oObject = new $sModelName" . '();');
return $oObject;
}
}
return new $sModelName();
You can call functions by a dynamic name as well: 您也可以通过动态名称调用函数:
$func = "foobar";
$func("baz"); //foobar("baz")
Yep, Kenaniah beat me to it. 是的,Kenaniah击败了我。 Gotta type faster...
打字速度更快...
More info here: http://php.net/manual/en/language.oop5.php , see the first user note . 此处的更多信息: http : //php.net/manual/en/language.oop5.php ,请参阅第一个用户说明 。
I know this is a 2 year old question, but I just want to point out, you all missed the question here! 我知道这是一个有2年历史的问题,但我只想指出,你们都错过了这里的问题! All your functions do not return an instantiated class, but a new class.
您的所有函数都不会返回实例化的类,而是返回一个新类。 This includes the initial function posted from the questioner!
这包括发问者发布的初始功能!
If you want to return an instantiated class , you have to keep track of your classes and their properties in an array, and return them from there when you require an instance of the class, instead of a re-initialised class. 如果要返回实例化的类 ,则必须跟踪数组中的类及其属性,并在需要该类的实例而不是重新初始化的类时从那里返回它们。
This method also saves a lot of processing time if your classes do a lot of processing when they are constructed. 如果您的类在构造时要进行大量处理,则此方法还可以节省大量处理时间。 It's always better to get an instance than to create a new class, unless you really want the class-properties re-initialized.
除非您确实希望重新初始化类属性,否则获取实例总是比创建新类更好。 Pay attention!
请注意!
Try: 尝试:
$m = new Model();
$m = $m->makeModel();
class Model {
public static function loadModel($sModelPath) {
if (!(strpos(' ' . $sModelPath, '/')>0)) {
$sModelPath .= '/' . $sModelPath;
}
$sModelName = str_replace('/','_',$sModelPath);
// P is a global var for physical path of the website
require_once(P . '_models/' . $sModelPath . '.php');
function makeModel(){
$model = new $sModelName;
return $model;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.