If I have an abstract class like this:
abstract class MyApp
{
public function init()
{
$this->stuff = $this->getStuff();
}
public function getStuff()
{
return new BlueStuff();
}
}
And then I have a class that extends from this abstract class like this:
class MyExtendedClass extends MyApp
{
public function init()
{
parent::init();
}
public function getStuff()
{
return new RedStuff();
}
}
If I do:
$myobj = new MyExtendedClass();
$myobj->init();
Why does the method getStuff from the child class get called? Isn't $this in the context of the abstract class? If so, shouldn't the method of the abstract class get called?
Thanks!
New answer
In PHP you can use subclasses as if all methods in the parent class that don't exist in the subclass have been copied to the subclass. So your example would be the same as:
class MyExtendedClass extends MyApp {
public function init() {
$this->stuff = $this->getStuff();
}
public function getStuff() {
return new RedStuff();
}
}
Just think of the subclass as having all code of the parent class and you're normally all right. There is one exception to this rule: properties. A private property of a class can only be accessed by that class, subclasses can't access the private properties of parent classes. In order to do that you need to change the private property into a protected property.
Original answer
Abstract classes in PHP are just like regular classes with one big difference: they can't get initiated. This means you can't do new AbstractClass();.
Since they work exactly like regular classes for everything else, this also is the case for extending classes. This means that PHP first tries to find the method in the initiated class, and only looks in the abstract classes if it doesn't exist.
So in your example this would mean that the getStuff() method from MyExtendedClass is called. Furthermore, this means you can leave out the init() method in MyExtendedClass.
Related
I have a base class and I want to have one of its methods called after the extending class is constructed. Ideally this should happen without changing the extended class constructor:
class BaseClass {
protected function doSomethingAfterConstruct() {}
}
class ExtendedClass extends BaseClass {
public function __construct() {
// some custom constructor code
}
}
I could just call $this->doSomethingAfterConstruct() at the end of the ExtendedClass constructor or by calling parent::__construct, but I am looking for a solution where I can implement this behavior by only changing the baseclass.
If it would be not __constructor, but ordinary method, then you can use __call magic method to proxy calls to child class:
All child methods should be non-public visibility, to trigger magic method
class BaseClass {
public function __call($name, $arguments) {
$return = $this->{$name}(...$arguments);
$this->doSomethingAfterMethod();
return $return;
}
protected function doSomethingAfterMethod() {}
}
class ExtendedClass extends BaseClass {
private function randomMethod() {
// some custom method code
}
}
I've already read Why does PHP 5.2+ disallow abstract static class methods? and How to force an implementation of a protected static function - the second is very similar to my case - but I am still without answer. Basically, I want to assure, that every child of my abstract class has implementation of protected static method, without implementing it as this has no meaning and because of lack of key informations there. Also, it must be static (because caller method is static and it has no context) and protected (so I cannot use interface, and I do not want anyone to call it directly), and it will be called by late static binding. Any ideas?
Dummy code below to illuminate my case:
abstract class BaseClass {
public static function foo() {
// some common stuff
static::bar();
// rest of common stuff
}
public function whoooaaa($condition) {
if ($condition) {
AClass::foo();
} else {
BClass::foo();
}
}
}
class AClass extends BaseClass {
protected static function bar() {
// do something
}
}
class BClass extends BaseClass {
protected static function bar() {
// do something else
}
}
// end somewhere else in my code, two constructions, both used:
AClass::foo();
// ....
$baseClassInheritedInstance->whoooaaa($variableCondition);
My only solution, ugly one, is to implement dummy protected static method in base class and throw a generic exception, so that it must be implemented by inheritance.
You can add a static factory that will fill context for casual objects.
class Factory() {
public static getObject($condition) {
$object = $condition ? new A() : new B();
// you can fill context here and/or use singleton/cache
return $object;
}
}
abstract class Base {
abstract function concreteMethod();
}
class A extends Base {...}
class B extends Base {...}
i have become a bit confused about abstract class ! i have read more of the post written in stackoverflow and another website but i didn't understand ! so i took a look at my book again but i didn't understand it either . so please analyze the code below step by step :
thanks in advance
<?php
abstract class AbstractClass
{
abstract protected function getValue();
public function printOut() {
print $this->getValue();
}
}
class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}
}
class ConcreteClass2 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass2";
}
}
$class1 = new ConcreteClass1;
$class1->printOut();
$class2 = new ConcreteClass2;
$class2->printOut();
?>
By definition
'An abstract class is a class that is declared abstract —it may or may
not include abstract methods. Abstract classes cannot be instantiated,
but they can be subclassed. An abstract method is a method that is
declared without an implementation'.
If defined an abstract class, you should extend that class with another.
In case of having abstract methods within the abstract class, you should write them in the child class in order to instantiate the child.
Related to the code, that is why when you instantiate the ConcreteClass, the getValue function is 'overwritten' to the pattern, while calling to the printOut method is from the father itself, because It is already written and not overwritten by the child. (See also that method was not abstract, that is why you can also use it from the father class)
Your code is right. Abstact class mean, when you can not make a instance of it. You can not do this:
$abstract = new AbstractClass();
What is the best of calling a method in child class. My IDE always shows Errors if i try to call the method directly.
class Base
{
public function DoIt()
{
$this->Generate(); //How to check if child implements Generate?
}
}
class Child extends Base
{
protected function Generate()
{
echo "Hi";
}
}
Simply put, you don't do this. It is very bad design: base classes should never assume anything about their descendants other than that they implement the contracts the base itself defines.
The closest acceptable alternative would be to declare abstract protected function Generate() on the parent so that it knows that all derived classes implement it. Of course this is not meant to be a mechanical solution: you should only do it if Generate is meaningful for all descendants of Base.
The issue is that your parent class doesn't define a Generate() method that a child class can override; you have to explicitly define this by creating an abstract method:
// class with at least one abstract method is
abstract class Base
{
public function DoIt()
{
$this->Generate();
}
// child classes MUST implement this method
abstract protected function Generate();
}
You can loosen the requirements by creating an empty implementation in the parent class:
class Base
{
public function DoIt()
{
$this->Generate();
}
// child classes MAY implement this method
protected function Generate() {}
}
Having the following class hierarchy:
class TheParent{
public function parse(){
$this->validate();
}
}
class TheChild extends TheParent{
private function validate(){
echo 'Valid!!';
}
}
$child= new TheChild();
$child->parse();
What is the sequence of steps in which this is going to work?
The problem is when I ran that code it gave the following error:
Fatal error: Call to private method TheChild::validate() from context 'TheParent' on line 4
Since TheChild inherits from TheParent shouldn't $this called in parse() be referring to the instance of $child, so validate() will be visible to parse()?
Note:
After doing some research I found that the solution to this problem would either make the validate() function protected according to this comment in the PHP manual, although I don't fully understand why it is working in this case.
The second solution is to create an abstract protected method validate() in the parent and override it in the child (which will be redundant) to the first solution as protected methods of a child can be accessed from the parent?!!
Can someone please explain how the inheritance works in this case?
Other posters already pointed out that the mehods need to be protected in order to access them.
I think you should change one more thing in your code. Your base class parent relies on a method that is defined in a child class. That is bad programming. Change your code like this:
abstract class TheParent{
public function parse(){
$this->validate();
}
abstract function validate();
}
class TheChild extends TheParent{
protected function validate(){
echo 'Valid!!';
}
}
$child= new TheChild();
$child->parse();
creating an abstract function ensures that the child class will definitely have the function validate because all abstract functions of an abstract class must be implemented for inheriting from such a class
Your idea of inheritence is correct, just not the visibility.
Protected can be used by the class and inherited and parent classes, private can only be used in the actual class it was defined.
Private can only be accessed by the class which defines, neither parent nor children classes.
Use protected instead:
class TheParent{
public function parse(){
$this->validate();
}
}
class TheChild extends TheParent{
protected function validate(){
echo 'Valid!!';
}
}
$child= new TheChild();
$child->parse();
FROM PHP DOC
Visibility from other objects
Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects.
Private can only be accessed by the class which defines or Same object type Example
class TheChild {
public function parse(TheChild $new) {
$this->validate();
$new->validate(); // <------------ Calling Private Method of $new
}
private function validate() {
echo 'Valid!!';
}
}
$child = new TheChild();
$child->parse(new TheChild());
Output
Valid!!Valid!!