0

I am developing a class which will use credentials to obtain some information from a remote source. Those credentials are not going to change often, so they can be a part of the configuration. My question is, what is a better practice in PHP OOP:

  1. The class reads those credentials from the configuration on construction.

    public function __construct()  
    {  
        //get credentials from database, etc...  
    }
    
  2. The caller class provides them on construction as arguments.

    public function __construct($credentials)  
    {  
        //save them for later use  
    }
    
Debflav
  • 1,131
  • 7
  • 17

3 Answers3

1

The second example. Because you have less dependencies on other classes, thus higher re-usability.

This might be useful: Why should a web architecture be loosely coupled?

Community
  • 1
  • 1
sridesmet
  • 875
  • 9
  • 19
1

A class should never depend on variables from outside, other then parameters. If you construct your program that way, you can reuse your classes in other programs, or in the same program with other parameters. The question you should ask yourself: can i use this class again? In this case the answer is no.. So Give it as a parameter.

If you think its annoying to give the parameter over and over again. You could concider using dependencyinjections to automatically give the right parameters. Or use the factory pattern which construct the class based on the config.

Mark Smit
  • 582
  • 4
  • 12
-1

Number #1 : In some cases in database if you don't need to always initialize the value.

class Mysql{    
    public function __construct(){
        $conn = mysql_connect("localhost", "root", "") or die("Error");
        mysql_select_db("dbname",$conn) or die("Error");
    }

    public function inser_data(){
        // query here...
    }
}

Number #2 : It depends on the behavior of your class. If you need to set the value to operate well your class then you need to always fetch the data.

class Bike{
    var $speed;
    var $type;
    public function __construct($properties){
        $this->speed = $properties["speed"];
        $this->type = $properties["type"];
    }

    public function calculation(){
    // script here...
   }
}
Jan
  • 1
  • 1
  • 1
    Defenately not, Not even in the case of adatabase. What if you will have to include some data from a second database. Then this way there is no way to use this class for that connection. You will have to write total new class for this. In case of the bike, its personal preferences. But for the readability it would be better ot give more parameters. Simply because that tells the user what to expect. – Mark Smit Aug 25 '14 at 12:45