从php中的同名命名空间导入全局类

时间:2022-05-06 23:48:22

Using namespace in this scenario is totally clear, I create a new namespace called ArrayObject and I use that class for my needs.

在这种情况下使用命名空间是完全清楚的,我创建了一个名为ArrayObject的新命名空间,我根据自己的需要使用该类。

namespace NamespaceTesting;             

class ArrayObject{

    public $initVal;
    function __construct($a){
        $this->initVal = $a;
    }

    public function append($unusedVal){
        var_dump($this);
    }
} 

$a = new ArrayObject("test");
$a->append("unusedVal");

the questioni is, if I want to use the global class of ArrayObject, I thought i should put use ArrayObject just before to use my code, but it doesn't work. what's wrong?

问题是,如果我想使用ArrayObject的全局类,我想我应该使用ArrayObject之前使用我的代码,但它不起作用。怎么了?

namespace NamespaceTesting;             

class ArrayObject{

    public $initVal;
    function __construct($a){
        $this->initVal = $a;
    }

    public function append($unusedVal){
        var_dump($this);
    }
} 

// this is not working
use ArrayObject;

$a = new ArrayObject("test");
$a->append("unusedVal");

what am I interpreting wrongly? thank you

我错误地解释了什么?谢谢

2 个解决方案

#1


0  

namespace NamespaceTesting;        

class ArrayObject{

    public $initVal;
    function __construct($a){
        $this->initVal = $a;
    }

    public function append($unusedVal){
        var_dump($this);
    }
} 

// $a is an ArrayObject from global namespace, not from NamespaceTesting;
$a = new \ArrayObject();
$a->append("unusedVal");
var_dump($a);

#2


0  

You are creating the namespace NamespaceTesting and not ArrayObject And thus need to call it like so (Using namespaces)

您正在创建命名空间NamespaceTesting而不是ArrayObject因此需要像这样调用它(使用命名空间)

use NamespaceTesting;

If you want to use the built in ArrayObject class.. you need to precede it with a slash

如果要使用内置的ArrayObject类,则需要在其前面加斜杠

$a = new \ArrayObject("test");

#1


0  

namespace NamespaceTesting;        

class ArrayObject{

    public $initVal;
    function __construct($a){
        $this->initVal = $a;
    }

    public function append($unusedVal){
        var_dump($this);
    }
} 

// $a is an ArrayObject from global namespace, not from NamespaceTesting;
$a = new \ArrayObject();
$a->append("unusedVal");
var_dump($a);

#2


0  

You are creating the namespace NamespaceTesting and not ArrayObject And thus need to call it like so (Using namespaces)

您正在创建命名空间NamespaceTesting而不是ArrayObject因此需要像这样调用它(使用命名空间)

use NamespaceTesting;

If you want to use the built in ArrayObject class.. you need to precede it with a slash

如果要使用内置的ArrayObject类,则需要在其前面加斜杠

$a = new \ArrayObject("test");