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

编程入门 行业动态 更新时间:2024-10-28 00:22:49
本文介绍了带有变量类名和命名空间的 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 静态方法调用

本文发布于:2023-11-11 23:57:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579906.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   静态   方法   空间   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!