带有变量类名和命名空间的 PHP 静态方法调用 [英] PHP static method call with variable class name and namespaces

查看:24
本文介绍了带有变量类名和命名空间的 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);

这篇关于带有变量类名和命名空间的 PHP 静态方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆