PHP - Object-oriented programming (OOP) Advanced Basics
Official doc : Classes and Objects
Method can specify the return type, the ? operator can be use to specify that it can return also null. copy to clipboard
copy to clipboard
Interfaces are defined in the same way as a class, but with the interface keyword replacing the class keyword and without any of the methods having their contents defined.
All methods declared in an interface must be public; this is the nature of an interface.
copy to clipboard
copy to clipboard
An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.
copy to clipboard
More precisely, late static bindings work by storing the class named in the last "non-forwarding call". In case of static method calls, this is the class explicitly named (usually the one on the left of the :: operator); in case of non static method calls, it is the class of the object. A "forwarding call" is a static one that is introduced by self::, parent::, static::, or, if going up in the class hierarchy, forward_static_call(). The function get_called_class() can be used to retrieve a string with the name of the called class and static:: introduces its scope.
This feature was named "late static bindings" with an internal perspective in mind. "Late binding" comes from the fact that static:: will not be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a "static binding" as it can be used for (but is not limited to) static method calls.
copy to clipboard
copy to clipboard
Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.
PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants. Here is an example of namespace syntax in PHP:
copy to clipboard
In PHP 5, this is no longer necessary. The spl_autoload_register() function registers any number of autoloaders, enabling for classes and interfaces to be automatically loaded if they are currently not defined. By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error.
this will be automated and seen later in composer autoloader...
Method typing
Arguments can be typed by setting his type before.Method can specify the return type, the ? operator can be use to specify that it can return also null. copy to clipboard
//Class definition class Demo { //an attribute private $attribute; //getter method return string or null public function getAttribute() : ?string { return $this->attribute; } //setter method with string argument return current object type Demo public function setAttribute(string $attribute) : Demo { $this->attribute=$attribute; return $this; } } //Instantiation $demo = new Demo; //display the class attribute $attribute value (as it is not set, will return null) echo $demo->getAttribute();
Traits
Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.copy to clipboard
// Declare the interface 'iDemo' trait tDemo { //an attribute private $attribute; //a getter method public function getAttribute() : ?string { return $this->attribute; } //a setter method public function setAttribute(string $attribute) : Demo { $this->attribute=$attribute; return $this; } } //Class definition class Demo implements iDemo { //apply the trait to the class (like an include) use tDemo; //class construcor public function __construct(string $attribute) { $this->setAttribute($attribute); } } //Instantiation $demo = new Demo("This is a test"); //display the class attribute $attribute value echo $demo->getAttribute();
Interfaces
Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.Interfaces are defined in the same way as a class, but with the interface keyword replacing the class keyword and without any of the methods having their contents defined.
All methods declared in an interface must be public; this is the nature of an interface.
copy to clipboard
// Declare the interface 'iDemo' interface iDemo { public function setAttribute($attribute); public function getAttribute(); } //Class definition that implement the interface iDemo class Demo implements iDemo { //an attribute private $attribute; //a method that must exist and have same signature as interface public function getAttribute() : ?string { return $this->attribute; } //a method that must exist and have same signature as interface public function setAttribute(string $attribute) : Demo { $this->attribute=$attribute; return $this; } //class construcor public function __construct(string $attribute) { $this->setAttribute($attribute); } } //Instantiation $demo = new Demo("This is a test"); //display the class attribute $attribute value echo $demo->getAttribute();
Anonymous classes
Support for anonymous classes was added in PHP 7. Anonymous classes are useful when simple, one-off objects need to be created.copy to clipboard
$util->setLogger(new class { public function log($msg) { echo $msg; } });
Object Cloning
Creating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.
copy to clipboard
//Clone $object into $copy_of_object $copy_of_object = clone $object;
Late Static Bindings
As of PHP 5.3.0, PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance.More precisely, late static bindings work by storing the class named in the last "non-forwarding call". In case of static method calls, this is the class explicitly named (usually the one on the left of the :: operator); in case of non static method calls, it is the class of the object. A "forwarding call" is a static one that is introduced by self::, parent::, static::, or, if going up in the class hierarchy, forward_static_call(). The function get_called_class() can be used to retrieve a string with the name of the called class and static:: introduces its scope.
This feature was named "late static bindings" with an internal perspective in mind. "Late binding" comes from the fact that static:: will not be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a "static binding" as it can be used for (but is not limited to) static method calls.
Object Serialization
serialize() returns a string containing a byte-stream representation of any value that can be stored in PHP. unserialize() can use this string to recreate the original variable values. Using serialize to save an object will save all variables in an object. The methods in an object will not be saved, only the name of the class.copy to clipboard
//Class definition class Demo { //an attribute private $attribute; //class construcor public function __construct(string $attribute) { $this->attribute=$attribute; } } //Instantiation $demo = new Demo("This is a test"); //Serialize $demo object and store it in a file for example $serialized = serialize($demo); file_put_contents('store',$serialized); //get serialized $demo from the previous file and restore the object into $unserializeDemo $storedSerialized = file_get_contents('store'); $unserializeDemo = unserialize($storedSerialized);
Objects and references
A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.copy to clipboard
//Class definition class Demo { //an attribute private $attribute; //a setter method public function setAttribute(string $attribute) : Demo { $this->attribute=$attribute; return $this; } //a setter getter public function getAttribute() : string { return $this->attribute; } //class construcor public function __construct(string $attribute) { $this->attribute=$attribute; } } //Instantiation $demo = new Demo("This is a test"); //create a reference $demoReference = &$demo: //change attritube in $demo and $demoReference are they are referenced $demoReference->setAttribute("Test has changed"); //display the result echo $demo->getAttribute();
Namespaces
In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions:Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.
PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants. Here is an example of namespace syntax in PHP:
copy to clipboard
//Namespace delcaration namespace App\Model; //call Class from namespace call use \App\Model\Demo; //Class from namespace call with alias use \App\Model\Demo as DemoAlias; //call function from namespace call use function \App\Model\function //call constant from namespace call use const \App\Model\constant //multiple call use \App\Model\User use \App\Model\Group //can be write use \App\Model\{User,Group}
- same namespace can be set in diffferente class file.
Autoloading Classes
Many developers writing object-oriented applications create one PHP source file per class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).In PHP 5, this is no longer necessary. The spl_autoload_register() function registers any number of autoloaders, enabling for classes and interfaces to be automatically loaded if they are currently not defined. By registering autoloaders, PHP is given a last chance to load the class or interface before it fails with an error.
this will be automated and seen later in composer autoloader...