有些功能无法正常使用命名空间
<?php
namespace MyApp;
class Fruit {}
class Apple extends Fruit {}
$apple = new Apple();
$name = 'Apple';
var_dump (is_subclass_of($apple, 'Fruit'));
var_dump (is_a($apple, 'Apple'));
var_dump (new $name);
如何使这兼容php 5.3和php&lt; 5.3没有命名空间支持? is_subclass_of和is_a不是这样的!
答案 0 :(得分:8)
<?php
namespace MyApp;
class Fruit {}
class Apple extends Fruit {}
$apple = new Apple();
$name = 'MyApp\Apple';
var_dump (is_subclass_of($apple, 'MyApp\Fruit'));
var_dump (is_a($apple, 'MyApp\Apple'));
var_dump (new $name);
您需要在将类名作为字符串而非裸字的函数中完全限定您的命名空间名称。作为裸字的类在运行时被解析。 Here's the PHP manual on namespace resolution和here's a page with examples using strings to fully qualify namespaces。
(另请注意单引号以防止反斜杠咀嚼。)