Hey, I'm quite experienced with PHP but I have no idea what the keyword abstract does when it comes down to object orientated programming. Can anyone explain in plain english what it can be used for?
What situations would I use the abstract keyword in? How does it change the class/interface?
We use abstract classes when we want to commit the programmer (either oneself or someone else) to write a certain class method, but we are only sure about the name of the method, and not the details of how it should be written. To take an example, circles, rectangles, octagons, etc.
An abstract function has no implemention and it can only be declared on an abstract class. This forces the derived class to provide an implementation. A virtual function provides a default implementation and it can exist on either an abstract class or a non-abstract class.
Interface are similar to abstract classes. The difference between interfaces and abstract classes are: Interfaces cannot have properties, while abstract classes can. All interface methods must be public, while abstract class methods is public or protected.
PHP has abstract classes and methods. Classes defined as abstract cannot be instantiated, and any class that contains at least one abstract method must also be abstract.
(Hope this is simple enough -- I don't think I can do better ^^ )
An abstract
class can not be instanciated : you can only create another class that inherits from the abstract
class, and instanciate that child class.
And if you declare some methods as abstract
, those must be defined in the child class, for that one to be instanciable.
Declaring a class abstract means that it must be subclassed in order to be used. An abstract class can not be instantiated. One can see it as an extended interface that might include implementation code (as opposed to an interface).
By declaring a method abstract, you force the sub class to implement the method.
The definition is mentioned above, now I will try to give you an example:
"abstract" ensures that you follow a specific logic, e.g. a ticket's material is ALWAYS "paper", or a creditcard must always have a "code". This is important if you work in a big company which has strict standardisation or if you want to 'force' your developers to follow a specific structure, so their code won't end up in a mess.
abstract class ticket{
public function material()
{
return 'Paper';
}
}
abstract class creditcard{
public function material()
{
return 'Plastic';
}
abstract function setCode(); // the ";" semicolon is important otherwise it will cause an error
}
class key extends ticket{
public function getMaterial()
{
return parent::material();
}
}
class anotherKey extends creditcard{
public function setCode($code)
{
$this->code = $code;
}
}
If we do not define the "setCode" method the parser will return an error on "new anotherKey
"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With