I have wrote simple class that allowing database selection and inserts.Could you please tell me does this a right way to use __call method with any useful advantage of it ?

class _getDatabase
    public $db;

   public function __construct(PDO $connection)
        $this->db = $connection;
  public function __call($function, $args) {

          if ($function == 'getSelect') {
            $sql = $this->db->prepare($args[0]['query']);
            return $sql->fetchALL(PDO::FETCH_OBJ);

           if ($function == 'getInsert') {
            $sql = $this->db->prepare($args[0]['query']);
            $result = $sql->execute($args[0]['parameters']);
            return $result;

$dbh = new PDO("mysql:host=;dbname=" . DATABASE, USERNAME, PASSWORD, array(
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception
$dbFactory = new _getDatabase($dbh);
$select = array();
$insert = array();
$select['query'] = 'SELECT * FROM `branches` WHERE B_CODE = ?';
$select['parameters'] = 'AMB';

$insert['query'] = 'INSERT INTO `commition`(`date`, `reg`, `com`, `oper`) VALUES (?,?,?,?)';
$insert['parameters'] = array('2014-02-20','86869','DITEC','Asuntha');
  • \$\begingroup\$ What do you think? Have you used this class to a demonstrable advantage? \$\endgroup\$
    – Dan Lugg
    May 1, 2014 at 11:50
  • \$\begingroup\$ i used this.But i can't figure out how this will useful with actual environment \$\endgroup\$
    – underscore
    May 1, 2014 at 11:52

1 Answer 1


You are using the __call for a completly wrong purpose. Instead of defining the functions/methods in the class itself, you are in fact defining them in a __call function.

Everytime you call a method on your current class the compiler does this:

doest the method exist? does the scope have privileges to call the method? -> call the method.

No method found? doest the object have a __call method? does the scope have privileges to call the method? -> call the method.

Now you are in the __call method. It now does a lot of string comparisons (could be 'optmized' using switch statements if a lot of calls are made).

Not really optimal, not to mention that the compiler and or other developers now have no clue at all or it/they are passing enough arguments to a method. hell

But, what is the point of the __call method then you may ask. Some argue this should never have been implemented in the first place, some love it. But that is a different argument.

Some neat examples:

  • \$\begingroup\$ Great explanation \$\endgroup\$
    – bumperbox
    May 5, 2014 at 19:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.