John Davidson

inheritance - PHP Calling a method in instantiated class from parent class

0 comments
Message:


I have a parent class with below code:


class ParentClass {
public function parentMethod()
{
if (childMethodExist()) {
$this->childMethod();
}
}
}

class ChildClass extends ParentClass {
public function childMethod()
// statement 1
// statement 2
}
}

Now I want to call parentMethod() which will intern call childMethod(). My problem is am I doing this correct (I already get eslint errors for $this->childMethod(); in VSCode). But the code works as I expect.



My Answer:
>childMethod();_ } else {_ echo "Child method does not exist";_ }_ }_}_And I have a child class that extends the ParentClass with below code:_class ChildClass extends ParentClass {_ public function childMethod()_ {_ echo "Child method called";_ }_}_Now, when I instantiate the ChildClass and call the parentMethod, it should check if the childMethod exists in the ChildClass and then call it. If the childMethod exists, it should print "Child method called". Otherwise, it should print "Child method does not exist".

Here is how you can achieve this:

php
class ParentClass {
public function parentMethod()
{
if (method_exists($this, 'childMethod')) {
$this->childMethod();
} else {
echo "Child method does not exist";
}
}
}

class ChildClass extends ParentClass {
public function childMethod()
{
echo "Child method called";
}
}

$childObj = new ChildClass();
$childObj->parentMethod();


When you run the above code, it will output "Child method called" because the childMethod exists in the ChildClass. If you remove the childMethod from the ChildClass, it will output "Child method does not exist".

Rate this post

3 of 5 based on 1654 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us