具有可变类名和名称空间的PHP静态方法调用 [英] PHP static method call with variable class name and namespaces
问题描述
我正在尝试从具有相同名称空间的另一个类中为名称空间类调用静态方法.但是另一个类的名称包含在一个变量中:
I'm trying to call a static method for a namespaced class from another class with the same namespace. But the other class' name is contained in a variable :
<?php
namespace MyApp\Api;
use \Eloquent;
class Product extends Eloquent {
public static function find($id)
{
//....
}
public static function details($id)
{
$product = self::find($id);
if($product)
{
$type = $product->type; // 'Book'
$product = $type::find($product->id);
return $product;
}
}
}
这是Book
类:
<?php
namespace MyApp\Api;
use \Eloquent;
class Book extends Eloquent {
public static function find($id)
{
//....
}
}
我的类型变量在Book
处包含有效的类名.此类位于相同的文件夹中,并使用相同的名称空间.
此代码返回错误Class 'Book' not found
.
我已经尝试了使用反斜杠或call_user_func
函数的几种变体(来自于我发现的SO问题),但是没有任何效果.
有人知道怎么了吗?
My type variable contains a valid class name here Book
. This class is in the same folder, and uses the same namespace.
This code returns the error Class 'Book' not found
.
I have tried several variations (from the SO questions I found) using backslashes, or the call_user_func
function, but nothing worked.
Anyone knows what's wrong ?
推荐答案
在使用变量引用您的类时,需要使用完全限定的名称.试试这个...
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);
这篇关于具有可变类名和名称空间的PHP静态方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!