【问题标题】:PHP static method call with variable class name and namespaces带有变量类名和命名空间的 PHP 静态方法调用
【发布时间】:2014-01-31 07:53:28
【问题描述】:

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

<?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 问题),但没有任何效果。 有谁知道怎么回事?

【问题讨论】:

    标签: php namespaces static-methods


    【解决方案1】:

    当使用一个变量来引用你的类时,你需要使用一个完全限定的名字。试试这个...

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

    【讨论】:

      【解决方案2】:

      @Phil 指出了正确的解决方案。

      为了更完整的观点,我澄清说,在访问全局命名空间之外的静态方法或属性时,完全限定名称是必需的。

      当访问 动态 方法或属性(我是指实例的属性) 没有限定名称时,PHP 会自动在当前命名空间内查找属性。

      在我看来,这种不对称性是没有用的,因为调用外部命名空间属性的机会对于静态或动态属性都是一样的。

      (目前在 PHP 7.2.0 上有效)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-10
        • 1970-01-01
        • 2014-11-13
        • 2011-09-28
        • 1970-01-01
        相关资源
        最近更新 更多