PHP static method call with variable class name and namespaces

断了今生、忘了曾经 提交于 2019-11-29 09:52:39
Phil

When using a variable to reference your class, you need to use a fully qualified name. Try this...

$type = __NAMESPACE__ . '\\' . $product->type;
$product = $type::find($product->id);

@Phil pointed out the right solution.

For a more complete point of view, I clarify that the fully qualified name is necessary when accessing static methods or attributes, out of the global namespace.

When accessing dynamic methods or attributes (I mean properties of an instance) without qualifying the name, PHP automatically looks for the property inside the current namespace.

In my opinion this asymmetry is not useful, as the opportunity to invoke foreign namespace properties are equal either for static or dynamic properties.

(Valid on PHP 7.2.0 at the moment I am writing).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!