March 25, 2012

Working with extended classes in PHP

Question by epic_syntax

I have 2 classes looking like this:

class db {

    protected $db;

    function __construct() {
        $this->connect();
    }

    protected function connect() {
        $this->db = new MySQLi(db_host, db_user, db_pass, db_name) or die($this->db->error);
        $this->db->set_charset('utf8');
    }

}

and

class sample extends db {

    protected $js_base_dir;

    public function __construct($js_base_dir = js_dir) {
        $this->js_base_dir = $js_base_dir . "/";
    }
 ....

I want to use $this->db inside second class, but __construct in sample class overrides first classes construct function. How to get $this-> db inside second class? Am I doung something wrong? if yes what’s proper way?

Answer by Starx

You can call parent class method, using parrent::methodName(). Similarly, you can use this to invoke parent’s constructor method as well as

parent::__construct();

Usage:

public function __construct($js_base_dir = js_dir) {
    parent::_construct();
    $this->js_base_dir = $js_base_dir . "/";
}

Apart from the manual read this article for extended explanation.

July 10, 2011

how to "inject" built-in php functions

Question by gadelat

How can i modify returning value of built-in php function without creating new function with another name and renaming all of used functions with previous name to new one?
e.g.

function time() {
    return time()-1000;
}

Of course this won’t pass, isn’t there something like “function time() extends time() {}” or similar?

Answer by Paul Dixon

With the APD PECL extension you can rename and override built-in functions.

//we want to call the original, so we rename it
rename_function('time', '_time()');

//now replace the built-in time with our override
override_function('time', '', 'return my_time();');

//and here's the override
function my_time($){
        return _time()-1000;  
}

APD is intended for debugging purposes, so this isn’t a technique you should really consider for production code.

Answer by Starx

Why would you want to override PHP’s function anyway? If some function does not do what you exactly want, then create your own function. If it overrides, use a different name or create a class and put the function inside it.

What you are trying to achieve is a wrong solution for a problem!!!

Some examples

Instead of function name time() you can make cTime()(custom Time)
Just like I create my own function for print_r() as printr() to print array in my way

or something like

class FUNCTIONS {
    public function time() {
        return time()-1000;
    }
}
//Now access using
FUNCTIONS::time();
...

Please fill the form - I will response as fast as I can!