使用在 class 的构造方法中赋值的变量 else where 无需重新赋值

Using a variable with a value assigned in a class's construct method else where without re assigning value

我有基本的class:

class Customer {

  private $customer_info;
  private $mysqli;

  function __construct(Array $customer_info, Mysqli $mysqli) {
    $this->mysqli = $mysqli;
    $this->customer_info = $customer_info;
  }

}

在构造方法中,我为 mysqli 和 customer_info 变量赋值。

在每个方法中我都必须告诉它 $mysqli 是什么,但我觉得它只是在引用它自己。

public function get() {
  $mysqli = $this->mysqli;
  // carry out mysql things
}

如果我不包括该行,那么任何语句等都不起作用,无论如何我可以做到这一点,所以我不必在每个方法中继续做 $mysqli = $this->mysqli ?

不,那是不可能访问 class 变量,你应该使用 $this->myvar,除非你使用静态变量而不是像 self:$myvar

这样的变量

是的,你可以做到

将变量 public 设为静态 class。

public static $mysqli;

在任何你可以访问静态成员的地方,比如

$mysqli = Customer::mysqli;

但更好的方法是将变量设为私有并通过调用方法来使用它。

public function getSQLConn() {
  $mysqli = $this->mysqli;
  return $mysqli;
}

并value/use喜欢

$mysqli = $this->getSQLConn();