Traven
Traven

Reputation: 311

Init another class in construct method?

I am looking into trying to simplify my PHP code some more, and I have yet to find an answer with this methodology one of my team members are using. Nor, have I ever saw this done before anywhere on the web.

Here is the code example from our web application which he is working on with me.

<?php

class ArticlesHandler {
   public function __construct() {
      require 'Articles.php';
      $articles = new Articles;
   } 
}

?>

Is this proper to init one class within another class?

For me, this just seems not proper standard to init classes to work together.

Upvotes: 1

Views: 115

Answers (4)

Jay Bhatt
Jay Bhatt

Reputation: 5651

This is what I normally do.

class Repository {

     protected $_models = array();

     public function getModel($model, array $params = array()){
        require_once $model.'.php'; //Replace this with an autoloader
        if(empty($this->_models[$model])){

             if(!empty($params)){
                    $this->_models[$model] = new $model($params);
             } else {
                   $this->_models[$model] = new $model();
             }

         }

        return $this->_models[$model];
     }
} 

And call the other class like this.

   class ArticlesHandler extends Repository {
       public function __construct() {
          $articles = $this->getModel('Articles');
       } 
    }

Upvotes: 1

deceze
deceze

Reputation: 522032

Yes and no. It works, but this particular code can lead to a number of problems.

  1. You should be using require_once instead of require to avoid possible errors of including the same file twice. As it is this code here will bring your app to a complete stop:

    new ArticlesHandler;
    new ArticlesHandler;
    
  2. This creates a hard coupling to the Articles class. You should probably rather be using dependency injection and pass an instance of Article to the constructor of ArticlesHandler. See How Not To Kill Your Testability Using Statics.

Upvotes: 2

ashishmaurya
ashishmaurya

Reputation: 1196

it seem's right.
For me, this just seems not proper standard to init classes to work together.

you can extend Articles class if you want to use Articles class inside the ArticlesHandler

Upvotes: 0

lejlot
lejlot

Reputation: 66795

Yes, it is proper and normal to call constructors in a constructor. There is nothing weird/bad about it.

Upvotes: 1

Related Questions