在PHP7.0中,可以使用以下方式实现懒加载:
class MyClass {
private $lazyLoadedProperty;
public function getLazyLoadedProperty() {
if ($this->lazyLoadedProperty === null) {
$this->lazyLoadedProperty = function() {
// 懒加载的逻辑
return 'lazy loaded property';
};
}
return $this->lazyLoadedProperty();
}
}
class MyClass {
private $lazyLoadedProperty;
public function __get($name) {
if ($name === 'lazyLoadedProperty') {
if ($this->lazyLoadedProperty === null) {
$this->lazyLoadedProperty = 'lazy loaded property';
}
return $this->lazyLoadedProperty;
}
}
}
这两种方式都可以实现懒加载,具体选择哪种方式取决于个人的编码习惯和需求。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站