简体   繁体   English

在PHP中定义公共类变量的最佳方法

[英]Best method of defining a public class variable in PHP

Is there any difference between these methods of declaring and setting a public class variable? 这些声明和设置公共类变量的方法之间有什么区别吗? Is there any reason why you would choose one over the other? 你有什么理由选择其中一个吗?

Method 1 方法1

class example {

  public $myArray;

  function __construct() {
    $this->myArray = array(1, 2, 3);
  }

  function showVar() {
    print_r( $this->myArray );
  }

}

Method 2 方法2

class example {

  public $myArray = array(1, 2, 3);

  function showVar() {
    print_r( $this->myArray );
  }

}

In first case the code will be evaluated each time you create new class instance. 在第一种情况下,每次创建新的类实例时都会对代码进行评估。

In second case - it will be evaluated just once when class was parsed. 在第二种情况下-解析类时,它将只评估一次。

That's all. 就这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM