在__constructor函数PHP中创建新对象

Can I create a new object in __constructor() ? so then I can use the class in current class method.

Let say I have this class

class Config{

  public function configure($data){

  }
}

and I want to use Config in some of Myclass method like this :

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
   }

}

can I do like that above. or I must create new object frequently like this below:

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
  }
}

Since I was new in writing my own php oop code,I would like to know which method are efficient when I want to create one object and used it in many function . Thanks!

You could try

protected $objDb;

public function __construct() {
$this->objDb = new Db();
}

Please refer PHP DBconnection Class connection to use in another

See if it helps

Declare $conf first.try it -

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
   }

}

You can certainly instantiate a new object in the constructor. You can also pass an object into it.

class Foo
{
    private $bar;

    public function __construct(BarInterface $bar)
    {
        $this->bar = $bar;
    }
}

There's a whole concept around it called "Dependency Injection".

If you design your classes like this, you can always switch $bar for any other object which implements BarInterface.

Apart from the solutions given above, you can also extend it making the Config file a super class.

class Config{
  // create a constructor method
  public function __construct() {
    // some initialisation here
  }

  public function configure($data){

  }
}

Then you can extend this class in your code to make use of 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
   }

}

Hope this helps.