V
V
VisualIdeas2016-07-02 15:22:27
PHP
VisualIdeas, 2016-07-02 15:22:27

How to access the property of a child from the parent?

Good day to all.
There is a small abstraction over the database in the form:
The main class is Table, it has a tableName property that is used in all methods for building an sql query
Methods define standard actions with tables
Child classes are classes for each specific table, where the tableName property is equal to the name of a specific table.
In order for the standard methods to work correctly, I have to redefine them in the child class like this:

public static $tableName = 'drivers_models';

    public static function getItemsById($array)
    {
        parent::$tableName = self::$tableName;

        $data = parent::getItemsById($array);
        
        // ...

        return $data;
    }

How can I avoid copying code like this?
Is it possible to access the property of the child that called the method?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Abdula Magomedov, 2016-07-02
@VisualIdeas

This is called late static binding. instead of parent:: or self:: use static::.
More details here.

S
shaqster, 2016-07-02
@shaqster

Nightmare architecture.
Make the Table class abstract, make methods common to all child classes, abstract methods, tableName property - protected with an empty value. Redefine everything in child classes, work with Table abstraction in code, but with concrete instances.
The parent should not know anything about their children, it destroys the whole logic.

T
ThunderCat, 2016-07-02
@ThunderCat

And let me ask you, why do you need a static? Maybe I'm misunderstanding something? Isn't it easier to make a non-static method and create an instance and use $this normally?

D
Dmitry, 2016-07-02
@slo_nik

And if in a parent class to accept the necessary parameter?
something like that
or, without creating $tableName at all, pass a string with the table name as the second parameter...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question