简体   繁体   中英

Calling a child class function if not exist in parent class

I have a code like following ---

class CartItem{
    var $v;
    function __construct(){
        $this->f();
    }
    function f(){
         echo 'In parent';
    }
}

class m extends CartItem{
    function f(){
        echo 'In child';
    }
}

new m();

Now when creating instance of m()... it doesn't have any constructor, so it is calling parent classes constructor. Now inside that a function f is called.

What I want is - if class m() have defined function f()... is should call it instead of parent class's function f().

But anyway it is calling parent classes function, as it was called from parent's constructor, irrespective of child class/ context :(

You want to call in __construct() a method that is not defined in the class. This is a sign that the CartItem class is an abstract concept and you don't intend to instantiate it (because an instance of CartItem probably doesn't contain enough information or behaviour for your project).

An abstract concept is implemented using an abstract class that defines as much as it can and defines abstract methods to be implemented in the concrete classes that extend it. The method f() is such a method that cannot be defined in the abstract concept and has to be defined in each class that extend it:

abstract class CartItem
{
    public function __construct()
    {
        $this->f();
    }

    abstract protected function f();
}

class m extends CartItem
{
    protected function f()
    {
        // Implement behaviour specific to this class
    }
}

This is actually a really interesting question.

so, as I understand it, you're asking ( if this isnt right please say ):

can you call a function of a class that's extending a parent?

yes, you can... sort of, if the method in the child is static.

Take this example (Ive not used it in the constructor for simplicity of example, but it will work there too):

class ClassA {

    public function testMeAsWell() {
        return ClassB::testMe();
    }
}

class ClassB extends ClassA {

    static function testMe() {
        return 'do something';
    }
}

$child = new ClassB();
echo $child->testMe();

// outputs 'do something'


$parent = new ClassA();
echo $parent->testMeAsWell();

// also outputs 'do something'

the reason this works needs more research, but as a guess I would say that because PHP is compiled, it will know about both classes at run-time and therefore will be able to figure out what we wanted it to do.

So, further on, you want to use variables. Yes you can, but they would have to be static as well.

working example

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