PHP - Object-oriented programming (OOP) Basics
Starting with PHP 5, the object model was rewritten to allow for better performance and more features. This was a major change from PHP 4. PHP 5 has a full object model.
Official doc : Classes and ObjectsClass structure
-
Class
A Class is an new type with its main structure that is composed by its attributes & methods. -
Attributes
An attribute is a variable/constant in a class. -
Constants
A constant declared in a class. -
Methods
A method is a function in a class. -
Arguments
An argument is a method parameter. -
Object
An object is an instance of a class. -
Instantiation
An instantiation is the creation of a distinct object based on a class. -
Class members
A class member is a method or constant or attribute of this class, all class members are all methods, constants and attributes of it. -
Construtor
Is the class main method automatically called when an Instantiation is done. -
Signature
the signature includes the number of arguments, the types of arguments and the order of the arguments contained by a method.
Class definition
copy to clipboard//Class definition class Demo { }
Instantiation (creation of an Object)
copy to clipboard//The object $demo is an instance of the class Demo $demo = new Demo(); //it can be call without () if no arguments are specified in class constructor $demo = new Demo; //$demo type is Demo var_dump($object instanceof Demo); // true var_dump(is_a($object, 'Demo'); // true
- An object is typed of its Class.
Class members(attributes, constants and methods)
copy to clipboard//Class definition class Demo { //an attribute public $attribute; //a constant public const CONSTANT = 'constant value' ; //a method public function method() { } //called on instantiation public function __construct() { } }
The pseudo-variable $this
copy to clipboard//Class definition class Demo { //an attribute public $attribute; //a method that return $attribute value public function method() { return $this->attribute; } //the class constructor method that set classs attribute $attribute value public function __construct($attribute) { $this->attribute=$attribute; } } //instantiation of the class Demo $demo = new Demo("This is a test"); //call of the method method() of the object $demo echo $demo->method();
Magic methods
Method | Action |
---|---|
__construct() | is triggered on instantiation |
__destruct() | is triggered on object destruction |
__call() | is triggered when invoking inaccessible methods in an object context. |
__callStatic() | is triggered when invoking inaccessible methods in a static context. |
__get() | is utilized for reading data from inaccessible properties. |
__set() | is run when writing data to inaccessible properties. |
__isset() | is triggered by calling isset() or empty() on inaccessible properties. |
__unset() | is invoked when unset() is used on inaccessible properties. |
__invoke() | method is called when a script tries to call an object as a function. |
__clone() | is trigered when cloning an object object using clone. |
__sleep() | serialize($object) |
__wakeup() | unserialize($serializedObject) |
__toString() | allows a class to decide how it will react when it is treated like a string. echo $class |
__set_state() | is called for classes exported by var_export(). |
__debugInfo() | is called by var_dump() when dumping an object. |
Class concepts
- Visibility
- Inheritance
- Abstraction
Visibility (public, private, protected)
The visibility of a property, a method or (as of PHP 7.1.0) a constant can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inheriting and parent classes. Members declared as private may only be accessed by the class that defines the member.Official doc : Visibility
The 3 available Visibilities(public, private, protected) can be applied in the class to all its members(Properties, Constants and Methods).
- public
public scope to make that variable/function available from anywhere, other classes and instances of the object. - private
private scope when you want your variable/function to be visible in its own class only. - protected
protected scope when you want to make your variable/function visible in all classes that extend current class including the parent class.
Getter and Setter
The most common use of the visibility private/public case is the so called "Getter and Setter" methods.Getter : A function used to retrieve the value of some property of an object.
Setter : A function used to modify(set) the value of some property of an object.
copy to clipboard
//Class definition class Demo { //a private attribute that cannot be accessed outside the class private $attribute; //a public method that can be called from outside the class public function getAttribute() { return $this->attribute; } //a public method that can be called from outside the class public function setAttribute($attribute) { $this->attribute=$attribute; } } //instantiation of the class Demo $demo = new Demo; //set attribute into object $demo $demo->setAttibut("This is a test"); //get attribute into object $demo echo $demo->getAttibut(); //try to get attribute into object $demo, but will triger an error due to private access try{ echo $demo->attribute; } catch(Exeption $e){ echo "Error: cannot access to private attribute from outside the object"; var_dump($e); }
Inheritance (extends)
Inheritance is a well-established programming principle, and PHP makes use of this principle in its object model. This principle will affect the way many classes and objects relate to one another.Official doc : Object Inheritance
copy to clipboard
//Class definition class Parent { //a private attribute that cannot be accessed outside the class private $parentAttribute; } //class definition with Inheritance of the Parent class class Child extends Parent { //a public method that get $parentAttribute from Inheritance public function getParentAttribute() { return $this->parentAttribute; } //the magic method that will initialize $parentAttribute value public function __construct($value) { //set $parentAttribute from Inheritance $this->parentAttribute=$value; } } //set attribute into object $child $child->Child("This is a test"); //get attribute into object $child echo $child->getParentAttribute();
Final Keyword
PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.copy to clipboard
//Class definition class Parent { final public function test() { } } class Child extends Parent { public function test() { } } //Results in Fatal error: Cannot override final method Parent::test()
Abstraction (abstract)
PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature - they cannot define the implementation.Official doc : Class Abstraction
copy to clipboard
//Class definition as abstract abstract class AbstractClass { // Force Extending class to define this method abstract protected function getValue(); abstract protected function prefixValue($prefix); // Common method public function printOut() { print $this->getValue() . "\n"; } } //class definition with Inheritance of the AbstractClass class class ConcreteClass extends AbstractClass { //method forced to be declared protected function getValue() { return "ConcreteClass1"; } //method forced to be declared but visibility can be change public function prefixValue($prefix) { return "{$prefix}ConcreteClass1"; } }
- abstract class without Inheritance can only be accessed on static, the abstract class cannot be instanciated !
Scope Resolution Operator (::)
The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.copy to clipboard
//Class definition class Demo { const CONSTANT = 'A constant value'; } //static access to the constant echo Demo::CONSTANT;
Static Keyword
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can). copy to clipboard//Class definition class Demo { static const CONSTANT = 'A constant value'; } //instantiation of the class Demo $demo = new Demo; //static access to the constant echo $demo::CONSTANT; //try to read the constant CONSTANT dynamically try{ echo $demo->CONSTANT; } catch(Exeption $e){ echo "Error: access must be static using the Scope Resolution Operator"; var_dump($e); }
self::, parent::, static::
Three special keywords self, parent and static are used to access properties or methods from inside the class definition.When an extending class overrides the parents definition of a method, PHP will not call the parent's method. It's up to the extended class on whether or not the parent's method is called.
Child has test() | Parent has test() | ||
self::test() | YES | YES | Child test() is executed |
parent::test() | YES | YES | Parent test() is executed |
self::test() | YES | NO | Child test() is executed |
parent::test() | YES | NO | ERROR |
self::test() | NO | YES | Parent test() is executed |
parent::test() | NO | YES | Parent test() is executed |
self::test() | NO | NO | ERROR |
parent::test() | NO | NO | ERROR |