【问题标题】:PHP 5.3 namespaces - functions not working as expectedPHP 5.3 命名空间 - 函数未按预期工作
【发布时间】:2011-07-20 00:15:11
【问题描述】:

有些函数不能与命名空间一起正常工作

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

【问题讨论】:

  • 什么不能按预期工作?

标签: php namespaces


【解决方案1】:
<?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 resolutionhere's a page with examples using strings to fully qualify namespaces

(还要注意单引号以防止反斜杠咀嚼。)

【讨论】:

    猜你喜欢
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    • 2018-02-01
    • 2017-06-17
    • 1970-01-01
    • 2011-01-25
    相关资源
    最近更新 更多