PHP - 具有正确属性声明的抽象类

时间:2015-08-09 20:29:57

标签: php

我有我的抽象类:

class AbstractClass
{
    public function func($arguments)
    {
        // $this->array[0] (...)
    }
}

我的孩子班:

class ChildClass extends AbstractClass
{
    protected $array = [
        //(some content)
    ];
}

当我运行(new ChildClass)->func()时,我收到警告“属性数组不存在。”。我应该将属性array放在AbstractClass上还是只是忽略警告?

1 个答案:

答案 0 :(得分:1)

只需使用默认值将属性移至AbstractClass即可。 E.g。

class AbstractClass 
{                                                                                  
    protected $array = ['default'];                                                         

    public function show()                                                         
    {                                                                              
        print_r($this->array);                                                     
    }                                                                                                                                                          
}                                                                                  

class A extends AbstractClass                                                      
{                                                                                  
    protected $array =[1,2,3,4,5];                                           
}                                                                                  

class B extends AbstractClass                                                      
{                                                                                  
    protected $array =['A','B','C','D'];                           
}  

class C extends AbstractClass
{
   // use the defaults
}

echo (new A)->show();                                                              
echo (new B)->show();
echo (new C)->show();

输出

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => D
)
Array
(
    [0] => default
)

没有警告。