【发布时间】:2014-11-05 05:44:20
【问题描述】:
我可以在 __constructor() 中创建一个新对象吗?所以我可以在当前类方法中使用该类。
假设我有这门课
class Config{
public function configure($data){
}
}
我想在一些Myclass 方法中使用Config,如下所示:
include 'Config.php'
class Myclass {
function __construct(){
$this->conf = new Config(); //just create one config object
}
public function method1($data){
$this->conf->configure($data); //call the configure method
}
public function method2(){
$this->conf->configure($data); //call again the configure method
}
}
我可以像上面那样做吗?或者我必须像下面这样频繁地创建新对象:
class Myclass {
public function method1($data){
$this->conf = new Config(); //create config object
}
public function method2($data){
$this->conf = new Config(); //create again config object
}
}
由于我是编写自己的 php oop 代码的新手,我想知道当我想创建一个对象并在多个函数中使用它时哪种方法有效。谢谢!
【问题讨论】:
-
了解特殊对象 $this。这里如果你使用 $this->conf 意味着你必须以非静态方式声明这个属性来获取它。即
public $conf或protected $conf或private $conf -
为什么不扩展
Config文件? -
抱歉,我已经编辑了我的问题。我没有扩展 Config,因为我只是想在某些函数中使用 Config 方法,而不是全部。
-
@MalikPerang - 无论您是扩展它还是创建它的实例,在任何情况下您都可以访问它的公共变量/方法。扩展还有一个好处是可以访问
protected属性。根据您的要求选择。 -
哦,我明白了......谢谢你的想法,先生!