Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/243.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在PHP7中首次访问时初始化对象属性?_Php_Oop - Fatal编程技术网

如何在PHP7中首次访问时初始化对象属性?

如何在PHP7中首次访问时初始化对象属性?,php,oop,Php,Oop,假设我有一门课: classdb{ 私有数据库连接$连接; 私有字符串$databaseName; 公共函数构造($databaseName){ $this->databaseName=$databaseName; } 私有函数initConnection():void{ 如果(!isset($this->connection)){ $this->connection=newdbconnection($this->databaseName); } } 公共函数查询($str):数组{ $this

假设我有一门课:

classdb{
私有数据库连接$连接;
私有字符串$databaseName;
公共函数构造($databaseName){
$this->databaseName=$databaseName;
}
私有函数initConnection():void{
如果(!isset($this->connection)){
$this->connection=newdbconnection($this->databaseName);
}
}
公共函数查询($str):数组{
$this->initConnection();
返回$this->connection->query($str);
}
公共函数某物():void{
$this->initConnection();
$this->connection->something();
}
}
然后我有一些代码,它们可能会调用
->查询
/
->一些方法,这取决于具体情况

如何避免在必须使用
$this->connection
的每个地方调用
initConnection
? 我只想在它第一次被访问时初始化它

我已经尝试了神奇的方法
\uu get
,但是只有当
$connection
不在类定义中时才会调用它

另一种方法是创建一个访问器方法(
getConnection
),该方法调用
initConnection
,并使用
$this->getConnection()
(返回连接对象,而不是
void
)而不是
$this->connection
,但是,
initConnection
仍然会被免费调用


这种方法的问题是,我可能会意外地使用
$this->connection
而不是getter方法;有没有一种方法可以禁止直接使用该属性?

在我看来,您的结论是正确的,即使用(private)
getConnection
方法仅在第一次使用时实例化连接。并让类方法的其余部分使用
getConnection()
而不是
$this->connection


然而,我也相信你正在经历单身模式的负面影响。也许考虑重构实际的<代码> dBooCT,并将其作为构造函数参数(依赖项)传递给<代码> dB<代码>。然后,您可以提供支持延迟加载和单例的
DBConnection
实现。

您使用的是哪个数据库(MySQL、Microsoft SQL Server等)?您正在使用哪个扩展(mysqli、PDO等)?请在你的问题上加上相应的标签。@dakis实际上,这个例子只是一个例子。我的问题不是关于数据库,而是关于类和属性初始化。