调试相关:为什么这个PHP代码不能与所需的行为一起工作


Debugging Related : Why does this PHP code not working with desired behavior?

我试图从示例示例中了解 php 命名空间中别名/导入 php.net/manual 用法。我稍微修改了示例示例,以在单个代码文件中探索 php 命名空间别名/导入的所有功能。我还在同一文件中添加了多个命名空间以观察所有功能。这是 php 源代码:

<?php
namespace foo{
echo "1-Inside namespace foo 'n";
use My'Full'Classname as Another;
use ArrayObject; // importing a global class
echo "2-After using  ArrayObject line: ".__LINE__."'n"; 
    class Another {
  public function cname() {
        echo "line".__LINE__."Method".__METHOD__."'n";       
   }
   static function  method(){echo "line".__LINE__."Method: ".__METHOD__."'n";}
} 
//This line below is Not working.
$obj1 = new namespace'Another; // instantiates object of foo'Another
echo "3-After namespace'Another object line: ".__LINE__."'n";
//This line below is Not working.
echo "4-".$obj1->method()."'n";
//This line below is Not working.
$obj2 = new Another; // instantiates object of class My'Full'Classname
echo "5-After Another object line: ".__LINE__."'n";
//This line below is Not working.
echo "6-".$obj2->method()."'n";
echo "7-After Another object line: ".__LINE__."'n";
//This line below is Not working.
$a = new ArrayObject(array(1)); // instantiates object of ArrayObject
echo "8-After ArrayObject line: ".__LINE__."'n";
}
namespace My'Full{
class Classname{
    public function cname() {
        echo "line".__LINE__."Method".__METHOD__."'n";       
   }
   static function  method(){echo "line".__LINE__."Method: ".__METHOD__."'n";} } }    
?>

我期望并希望打印这些所需的行为/输出,如下所示:

1-Inside namespace foo 
2-After using ArrayObject line: x
3-After namespace'Another object line: x
4-line: x Method: foo'Another:method()
5-After Another object line: x
6-line: x Method: My'Full'Classname:method()
7-After Another object line: x
8-After ArrayObject line: x

但是我没有得到所需的输出,而是只得到了几个输出,错误如下:

PHP Fatal error:  Cannot declare class foo'Another because the name is already in use in /home/himadree/ php workspace/ZCE/TOPIC1:BASICS/Namespaces/Using-namespaces-Aliasing-Importing.php on line 8

因此,看起来可能与类名另一个存在任何相同的命名冲突此外,我注意到类"Other"有2个版本:foo''Another & My''Full''Classname as Other.在一些有用的注释之后,我在命名空间foo中添加了额外的class'Other'。但它仍然不起作用。这是唯一的错误吗!我不知道。因此,为了获得我想要的行为/输出,此代码中需要进行哪些更改?我使用了 eclipse php pdt 工具,php 版本 5.5。由于这是调试问题,因此如果需要更具体的信息,请告诉我。谢谢

具体问题是没有定义foo/Another类。你在namespace foo内错过了这一点:

class Another {}

没有它或类似的东西,foo'Another就不存在,尝试像您一样实例化它将导致致命错误,就像它一样。

此外,我注意到类"Other"有2个版本:foo''Another & My''Full''Classname as Other。

这就是此代码试图演示的要点。只是Another会模棱两可,因为它可以引用别名as Anotherfoo'Another。因此,为什么namespace'Another被用来明确地指代foo'Another。与 new Another 相反,它指的是别名as Another