PHP:从变量中实例化一个类奇怪的失败 [英] PHP: Instantiating a class from a variable oddly fails
问题描述
我试图通过一个变量来实例化一个类(Laravel3雄辩模型),而且我收到一个错误,说没有找到该类。
当我对类名进行硬编码时,但是,它的工作原理很好。
(FYI,代码如下 $ contact_type
预计是电话,传真或电子邮件。)
I'm trying to instantiate a class (a Laravel3 Eloquent model) by a variable, and I'm getting an error saying that the class is not found.
When I hardcode the class name, though, it works just fine.
(FYI, in the code below $contact_type
is expected to either be Phone, Fax, or Email.)
这是我正在玩的时刻:
foreach( $input AS $contact_type => $contact_info )
{
foreach( $contact_info AS $data )
{
$obj = new $contact_type( (array)$data);
echo'<pre>Obj: ',print_r($obj),'</pre>'; // <----- For Testing
}
}
当我运行上面的代码时,它会引发一个 Class'Phone'not found 错误。
当我替换新$ contact_type()
与新的电话()
(或传真或电子邮件),它的工作很好。
我打赌有一些简单的我只是看看:)我缺少什么?
请帮助!
When I run the code as above, it throws a "Class 'Phone' not found" error.
When I replace new $contact_type()
with new Phone()
(or Fax or Email), it works just fine.
I bet there's something simple I'm just looking over :) What am I missing?
Please help!
推荐答案
The relevant manual entries that covers this are here and here. To quote the second link:
如果一个包含类的名称的字符串与new一起使用,则该类的新实例将被创建。如果类位于命名空间中,则在完成此操作时必须使用其完全限定名称。
If a string containing the name of a class is used with new, a new instance of that class will be created. If the class is in a namespace, its fully qualified name must be used when doing this.
这对我有用:
class Phone {}
$classtype = 'Phone';
$phone = new $classtype();
var_dump($phone);
生成输出:
object(Phone)#1 (0) {
}
查看以确保您不在命名空间中(如果您是字符串,请包括Phone类的名称空间)。或者,您也可以尝试使用反射:
Look to make sure you're not in a namespace (include the Phone class' namespace in the string if you are). Or, you can also try using reflection:
class Phone {}
$classtype = 'Phone';
$reflectionClass = new ReflectionClass($classtype);
$phone = $reflectionClass->newInstanceArgs();
var_dump($phone);
如果Phone类在命名空间中,这也可以:
If the Phone class is in a namespace, this also works:
Phone.php
<?php namespace Contact;
class Phone {}
test.php
<?php
include 'Phone.php';
$classtype = 'Contact\Phone';
$phone = new $classtype();
var_dump($phone);
我不是100%肯定为什么,虽然我怀疑当评估变量类名时命名空间映射不可见。考虑这个代码:
I'm not 100% sure why, although I suspect that when evaluating a variable class name the current namespace mappings aren't visible. Consider this code:
<?php namespace Foo;
use SomePackage\SomeClass as WeirdName;
$test = new WeirdName();
与以下项目进行比较:
<?php namespace Foo;
use SomePackage\SomeClass as WeirdName;
$class = 'WeirdName';
$test = new $class();
当PHP决定为新实例分配内存时,它将如何知道映射类名称别名 WeirdName
to SomePackage\Someclass
?该别名仅对当前文件有效,在 userland 代码,更不用说相同的文件。
When PHP decides to allocate memory for a new instance, how will it know to map the class name alias of WeirdName
to SomePackage\Someclass
? That alias is only valid for the current file, and the code that actually performs that operation isn't even in userland code, much less the same file.
这篇关于PHP:从变量中实例化一个类奇怪的失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!