PHP5. Two ways of declaring an array as a class member

后端 未结 4 1405
猫巷女王i
猫巷女王i 2021-02-07 00:43

When declaring an array as a class member, which way should it be done?

class Test1 {
    private $paths = array();

    public function __construct() {
                 


        
4条回答
  •  鱼传尺愫
    2021-02-07 01:09

    If you are going to populate your array dynamically during initialization, do it in the constructor. If it contains fixed values, do it in the property declaration.

    Trying to populate an array dynamically (e.g. by using the return value of a certain function or method) within the declaration results in a parse error:

    // Function call is not valid here
    private $paths = get_paths();
    

    Performance is not a real concern here as each has its own use case.

提交回复
热议问题