简体   繁体   中英

Calling a static parent method while instantiating child class

I'm changing my class structure around to store common database methods in one class. Then extending it from a child class. This should cut down on code but also allows me to overwrite the parent methods when I need to.

I've done the following, for this example I've simplified to the basics compared to the original code which contains more classes.

class parent_object{
    private $table_name;

    public function all_records(){
        $sql = "SELECT * FROM ".$this->table_name;
        return $this->execute_sql($sql);
    }
}

class child_object extends parent_object{
    protected static $table_name="tbl_name";

    public function __construct(){
        parent::__construct(self::$table_name);
    }
}

I want to call the all_records() statically to save myself creating a new object every time.

I'm stuck having to instantiate the child and then call the parent method

$child = new child_object();
$all = $child->all_records();

What I really want to be able to call the parent method statically:

$all = child_object::all_records();

I understand why I can't do it with my code, but would like some way that the child instantiates first then accesses the parent method.

I could write all_records() method in the child_object to instantiate itself and call the parent all_records() but that sort defeats the purpose of extending to cut down on code and the same methods in my child class.

I'm sure its quite simple or some new high level oop function can do it.

Thanks for your help.

The answer is relatively simple, you can turn all your properties into static properties, and then use static:: instead of self:: .

http://php.net/manual/en/language.oop5.late-static-bindings.php

Solving your problem this way is considered a bad practice though. Good luck.

You could do something like this:

class child_object extends parent_object
{
    protected static $table_name="tbl_name";

    public static function factory()
    {
        return new child_object();
    }

    public function __construct()
    {
       parent::__construct(self::$table_name);
    }
}

Then when you use it you just do:

$all = child_object::factory()->all_records();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM