开发者

PHP 5.3 namespaces - functions not working as expected

There are some functions not working properly with namespaces

<?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);

How can I make this compatible with both php 5.3 and php < 5.3 with no namespace support ? is_subclass_of and is_a are not working like this !


<?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);

You need to fully qualify your namespace name in functions that take a class name as a string instead of as a bareword. Classes as barewords are resolved at runtime. Here's the PHP manual on namespace resolution, and here's a page with examples using strings to fully qualify namespaces.

(Also note the single quotes to prevent backslash munching.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜