首页 > 技术文章 > php trait 变量类型为数组时 不能被父类子类同时use

naci 2016-10-20 15:42 原文

直接上代码

---------------------------

trait T1 {

        public static $a=1;

        public static $b= [];

        public static function getC(){

                echo 'class: ' . get_class() . "\n";

        }

}

 

class a{

        use T1;

}

 

class b extends a{

        use T1;

        public static function getHw(){

                echo 'Hello';

        }

}

b::getHw();

--------------

运行以上代码,错误信息

Fatal error: a and T1 define the same property ($b) in the composition of b. However, the definition differs and is considered incompatible. Class was composed 

---------------

此时把

public static $b= [];改为public static $b= 1;非数组的其他类型正常运行。

 

---------------

至于父类和子类都use T1,是为了让b::getC();取到的类名是b而不是a

 

 

推荐阅读