namespace,$this笔记

PHP支持两种抽象的访问当前命名空间内部元素的方法, __NAMESPACE__魔术常量和namespace关键字。

测试

<?php
namespace namespace2;
class innamespace2{
    function test(){
        include "namespace3.php";

    }
    function test2(){
        echo '在文件namespace2中'.__NAMESPACE__.PHP_EOL;

    }
}
(new innamespace2)->test();
new 
amespace3innamespace3;
include "namespace4.php";
<?php
/*文件namespace3.php*/
namespace namespace3;
/**
* 
*/
class innamespace3 
{
	
	function __construct()
	{
		# code...
		echo '在文件namespace3中'.__NAMESPACE__.PHP_EOL;


	}
}
(new 
amespace2innamespace2)->test2();

  

<?php
/*文件namespace4.php*/
namespace namespace4;
/**
* 
*/
class innamespace4 
{
    
    function __construct()
    {
        # code...
        echo '在文件namespace4中'.__NAMESPACE__.PHP_EOL;
        include "namespace5.php";
    }
}
new 
amespace4innamespace4;
new 
amespace5innamespace5;
/*文件namespace5.php*/
namespace namespace5;
/**
* 
*/
class innamespace5 
{
    
    function __construct()
    {
        # code...
        echo '在文件namespace5中'.__NAMESPACE__.PHP_EOL;
    }
}

结果

通过测试,得知

当前命名空间名称是根据执行上下文来判断的,而不是根据调用代码所在的位置

关于$this,是谁的实例?

<?php

(new C)->func();
class B{
    static $a=555;
    static public function astaticfunc($value='')
    {    
        echo "in static";
        //print_r($this);
    }
      public function func($value='')
    {    
        $this->astaticfunc();
        print_r($this);
    }

}


class C extends B{
}

结果是:in static C Object ( )

原文地址:https://www.cnblogs.com/ch459742906/p/5478617.html