带有变量类名和命名空间的 PHP 静态方法调用

2022-01-14 00:00:00 static-methods namespaces php

我正在尝试从具有相同命名空间的另一个类调用命名空间类的静态方法.但是另一个类的名称包含在一个变量中:

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 MyAppApi;
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 MyAppApi;
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);

相关文章