我有一个基本类:
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了?
不,不可能访问应该使用$this->myvar
的类变量,除非使用静态变量,否则可以调用self:$myvar
等变量
是的,你可以
在类中使变量为public和static。
public static $mysqli;
在任何地方你都可以访问像这样的静态成员
$mysqli = Customer::mysqli;
但更好的方法是将变量设为私有变量,并通过调用类似的方法来使用它。
public function getSQLConn() {
$mysqli = $this->mysqli;
return $mysqli;
}
获得价值/像一样使用
$mysqli = $this->getSQLConn();