4

I have a class hierarchy in PHP 5.2.9.

The base class has a protected property which is an associative array.

The child classes can add some elements to the array.

The child classes are declared in the separate files (plugins), which will be created and added by multiple developers.

Which is the best way to add the elements to the property in the child classes so that declaring a new child would be as simple as possible?

<?php
        class A {
                protected $myproperty = array (
                        'A1' => 1,
                        'A2' => 2
                );

                function myprint()
                {
                        print_r($this->myproperty);
                }
        };

        class B extends A {
                // add 'B1', 'B2' to myproperty
        };

        class C extends B {
                // add 'C1', 'C2' to myproperty
        };

        $c = new C();
        $c->myprint();
        // The line above should print A1, A2, B1, B2, C1, C2
?>

Ideally, I'd like to make it for the developers as simple as declaring a variable or a private property, without having a need to copypaste any code.

1 Answer 1

3

Make use of the constructors of the inherited classes, for class B it would become something like this:

class B extends A {
    function __construct() {
        parent::__construct();                // Call constructor of parent class
        array_push($myproperty, "B1", "B2");  // Add our properties
    }
}

Same goes for class C.

If you have a lot of inherited classes, or want to provide as much support as possible, you could put this code into some function. So the other developers only need to call this function in their constructor to 'register' their child.

Sign up to request clarification or add additional context in comments.

4 Comments

That's exactly what I first thought of, but is there a more simple way?
You could try to automate this process by using get_class() and add the properties in the constructor of class A. But I suppose this is much more complex (for you at least).
How do I do this using get_class()?
Get the class name from get_class(), add the name as a property. Or use this name to find the properties in a file or special function. As I said: much more complex for you.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.