我可以在__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代码,所以当我想创建一个对象并在多个函数中使用它时,我想知道哪种方法是有效的。谢谢
首先声明$conf
。重试-
include 'Config.php';
class Myclass {
private $conf;
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
}
}
您可以尝试
protected $objDb;
public function __construct() {
$this->objDb = new Db();
}
请参阅PHP DBconnection类连接以在另一个中使用
看看它是否有助于
您当然可以在构造函数中实例化一个新对象。你也可以把一个物体传给它
class Foo
{
private $bar;
public function __construct(BarInterface $bar)
{
$this->bar = $bar;
}
}
它有一个完整的概念,叫做"依赖注入"。
如果你这样设计你的类,你总是可以为任何其他实现BarInterface的对象切换$bar。
除了上面给出的解决方案外,您还可以扩展它,使Config
文件成为一个超级类。
class Config{
// create a constructor method
public function __construct() {
// some initialisation here
}
public function configure($data){
}
}
然后,您可以在代码中扩展此类以使用inheritance
。
include 'Config.php'
class Myclass extends Config {
function __construct(){
parent::__construct(); //initialise the parent class
// more initialisation
}
public function method1($data){
$this->configure($data); //call the configure method
}
public function method2(){
$this->configure($data); //call again the configure method
}
}
希望这能有所帮助。