Skip to main content

PHP OOP

PHP - What is OOP? From PHP5, you can also write PHP code in an object-oriented style. Object-Oriented programming is faster and easier to execute. PHP What is OOP? OOP stands for Object-Oriented Programming. Procedural programming is about writing procedures or functions that perform operations on the data, while object-oriented programming is about creating objects that contain both data and functions. Object-oriented programming has several advantages over procedural programming: OOP is faster and easier to execute OOP provides a clear structure for the programs OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug OOP makes it possible to create full reusable applications with less code and shorter development time Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You should extract out the codes that are common for the application, and place them at a single place and reuse them instead of repeating it. PHP - What are Classes and Objects? Classes and objects are the two main aspects of object-oriented programming. Look at the following illustration to see the difference between class and objects: class Fruit objects Apple Banana Mango Another example: class Car objects Volvo Audi Toyota So, a class is a template for objects, and an object is an instance of a class. When the individual objects are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties. PHP OOP - Classes and Objects A class is a template for objects, and an object is an instance of class. OOP Case Let's assume we have a class named Fruit. A Fruit can have properties like name, color, weight, etc. We can define variables like $name, $color, and $weight to hold the values of these properties. When the individual objects (apple, banana, etc.) are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties. Define a Class A class is defined by using the class keyword, followed by the name of the class and a pair of curly braces ({}). All its properties and methods go inside the braces: Syntax Below we declare a class named Fruit consisting of two properties ($name and $color) and two methods set_name() and get_name() for setting and getting the $name property: Example name = $name; } function get_name() { return $this->name; } } ?> Note: In a class, variables are called properties and functions are called methods! Define Objects Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values. Objects of a class is created using the new keyword. In the example below, $apple and $banana are instances of the class Fruit: Example name = $name; } function get_name() { return $this->name; } } $apple = new Fruit(); $banana = new Fruit(); $apple->set_name('Apple'); $banana->set_name('Banana'); echo $apple->get_name(); echo "
"; echo $banana->get_name(); ?> In the example below, we add two more methods to class Fruit, for setting and getting the $color property: Example name = $name; } function get_name() { return $this->name; } function set_color($color) { $this->color = $color; } function get_color() { return $this->color; } } $apple = new Fruit(); $apple->set_name('Apple'); $apple->set_color('Red'); echo "Name: " . $apple->get_name(); echo "
"; echo "Color: " . $apple->get_color(); ?> PHP - The $this Keyword The $this keyword refers to the current object, and is only available inside methods. Look at the following example: Example So, where can we change the value of the $name property? There are two ways: 1. Inside the class (by adding a set_name() method and use $this): Example name = $name; } } $apple = new Fruit(); $apple->set_name("Apple"); ?> 2. Outside the class (by directly changing the property value): Example name = "Apple"; ?> PHP - instanceof You can use the instanceof keyword to check if an object belongs to a specific class: Example PHP OOP - Constructor PHP - The __construct Function A constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)! We see in the example below, that using a constructor saves us from calling the set_name() method which reduces the amount of code: Example name = $name; } function get_name() { return $this->name; } } $apple = new Fruit("Apple"); echo $apple->get_name(); ?> Another example: Example name = $name; $this->color = $color; } function get_name() { return $this->name; } function get_color() { return $this->color; } } $apple = new Fruit("Apple", "red"); echo $apple->get_name(); echo "
"; echo $apple->get_color(); ?> PHP OOP - Destructor PHP - The __destruct Function A destructor is called when the object is destructed or the script is stopped or exited. If you create a __destruct() function, PHP will automatically call this function at the end of the script. Notice that the destruct function starts with two underscores (__)! The example below has a __construct() function that is automatically called when you create an object from a class, and a __destruct() function that is automatically called at the end of the script: Example name = $name; } function __destruct() { echo "The fruit is {$this->name}."; } } $apple = new Fruit("Apple"); ?> Another example: Example name = $name; $this->color = $color; } function __destruct() { echo "The fruit is {$this->name} and the color is {$this->color}."; } } $apple = new Fruit("Apple", "red"); ?> Tip: As constructors and destructors helps reducing the amount of code, they are very useful! PHP OOP - Access Modifiers PHP - Access Modifiers Properties and methods can have access modifiers which control where they can be accessed. There are three access modifiers: public - the property or method can be accessed from everywhere. This is default protected - the property or method can be accessed within the class and by classes derived from that class private - the property or method can ONLY be accessed within the class In the following example we have added three different access modifiers to the three properties. Here, if you try to set the name property it will work fine (because the name property is public). However, if you try to set the color or weight property it will result in a fatal error (because the color and weight property are protected and private): Example name = 'Mango'; // OK $mango->color = 'Yellow'; // ERROR $mango->weight = '300'; // ERROR ?> In the next example we have added access modifiers to two methods. Here, if you try to call the set_color() or the set_weight() function it will result in a fatal error (because the two functions are considered protected and private), even if all the properties are public: Example name = $n; } protected function set_color($n) { // a protected function $this->color = $n; } private function set_weight($n) { // a private function $this->weight = $n; } } $mango = new Fruit(); $mango->set_name('Mango'); // OK $mango->set_color('Yellow'); // ERROR $mango->set_weight('300'); // ERROR ?> PHP OOP - Inheritance PHP - What is Inheritance? Inheritance in OOP = When a class derives from another class. The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods. An inherited class is defined by using the extends keyword. Let's look at an example: Example name = $name; $this->color = $color; } public function intro() { echo "The fruit is {$this->name} and the color is {$this->color}."; } } // Strawberry is inherited from Fruit class Strawberry extends Fruit { public function message() { echo "Am I a fruit or a berry? "; } } $strawberry = new Strawberry("Strawberry", "red"); $strawberry->message(); $strawberry->intro(); ?> Example Explained The Strawberry class is inherited from the Fruit class. This means that the Strawberry class can use the public $name and $color properties as well as the public __construct() and intro() methods from the Fruit class because of inheritance. The Strawberry class also has its own method: message(). PHP - Inheritance and the Protected Access Modifier In the previous chapter we learned that protected properties or methods can be accessed within the class and by classes derived from that class. What does that mean? Let's look at an example: Example name = $name; $this->color = $color; } protected function intro() { echo "The fruit is {$this->name} and the color is {$this->color}."; } } class Strawberry extends Fruit { public function message() { echo "Am I a fruit or a berry? "; } } // Try to call all three methods from outside class $strawberry = new Strawberry("Strawberry", "red"); // OK. __construct() is public $strawberry->message(); // OK. message() is public $strawberry->intro(); // ERROR. intro() is protected ?> In the example above we see that if we try to call a protected method (intro()) from outside the class, we will receive an error. public methods will work fine! Let's look at another example: Example name = $name; $this->color = $color; } protected function intro() { echo "The fruit is {$this->name} and the color is {$this->color}."; } } class Strawberry extends Fruit { public function message() { echo "Am I a fruit or a berry? "; // Call protected method from within derived class - OK $this -> intro(); } } $strawberry = new Strawberry("Strawberry", "red"); // OK. __construct() is public $strawberry->message(); // OK. message() is public and it calls intro() (which is protected) from within the derived class ?> In the example above we see that all works fine! It is because we call the protected method (intro()) from inside the derived class. PHP - Overriding Inherited Methods Inherited methods can be overridden by redefining the methods (use the same name) in the child class. Look at the example below. The __construct() and intro() methods in the child class (Strawberry) will override the __construct() and intro() methods in the parent class (Fruit): Example name = $name; $this->color = $color; } public function intro() { echo "The fruit is {$this->name} and the color is {$this->color}."; } } class Strawberry extends Fruit { public $weight; public function __construct($name, $color, $weight) { $this->name = $name; $this->color = $color; $this->weight = $weight; } public function intro() { echo "The fruit is {$this->name}, the color is {$this->color}, and the weight is {$this->weight} gram."; } } $strawberry = new Strawberry("Strawberry", "red", 50); $strawberry->intro(); ?> PHP - The final Keyword The final keyword can be used to prevent class inheritance or to prevent method overriding. The following example shows how to prevent class inheritance: Example The following example shows how to prevent method overriding: Example PHP OOP - Class Constants PHP - Class Constants Constants cannot be changed once it is declared. Class constants can be useful if you need to define some constant data within a class. A class constant is declared inside a class with the const keyword. Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters. We can access a constant from outside the class by using the class name followed by the scope resolution operator (::) followed by the constant name, like here: Example Or, we can access a constant from inside the class by using the self keyword followed by the scope resolution operator (::) followed by the constant name, like here: Example byebye(); ?> PHP OOP - Abstract Classes PHP - What are Abstract Classes and Methods? Abstract classes and methods are when the parent class has a named method, but need its child class(es) to fill out the tasks. An abstract class is a class that contains at least one abstract method. An abstract method is a method that is declared, but not implemented in the code. An abstract class or method is defined with the abstract keyword: Syntax When inheriting from an abstract class, the child class method must be defined with the same name, and the same or a less restricted access modifier. So, if the abstract method is defined as protected, the child class method must be defined as either protected or public, but not private. Also, the type and number of required arguments must be the same. However, the child classes may have optional arguments in addition. So, when a child class is inherited from an abstract class, we have the following rules: The child class method must be defined with the same name and it redeclares the parent abstract method The child class method must be defined with the same or a less restricted access modifier The number of required arguments must be the same. However, the child class may have optional arguments in addition Let's look at an example: Example name = $name; } abstract public function intro() : string; } // Child classes class Audi extends Car { public function intro() : string { return "Choose German quality! I'm an $this->name!"; } } class Volvo extends Car { public function intro() : string { return "Proud to be Swedish! I'm a $this->name!"; } } class Citroen extends Car { public function intro() : string { return "French extravagance! I'm a $this->name!"; } } // Create objects from the child classes $audi = new audi("Audi"); echo $audi->intro(); echo "
"; $volvo = new volvo("Volvo"); echo $volvo->intro(); echo "
"; $citroen = new citroen("Citroen"); echo $citroen->intro(); ?> Example Explained The Audi, Volvo, and Citroen classes are inherited from the Car class. This means that the Audi, Volvo, and Citroen classes can use the public $name property as well as the public __construct() method from the Car class because of inheritance. But, intro() is an abstract method that should be defined in all the child classes and they should return a string. PHP - More Abstract Class Examples Let's look at another example where the abstract method has an argument: Example prefixName("John Doe"); echo "
"; echo $class->prefixName("Jane Doe"); ?> Let's look at another example where the abstract method has an argument, and the child class has two optional arguments that are not defined in the parent's abstract method: Example prefixName("John Doe"); echo "
"; echo $class->prefixName("Jane Doe"); ?> PHP OOP - Interfaces PHP - What are Interfaces? Interfaces allow you to specify what methods a class should implement. Interfaces make it easy to use a variety of different classes in the same way. When one or more classes use the same interface, it is referred to as "polymorphism". Interfaces are declared with the interface keyword: Syntax PHP - Interfaces vs. Abstract Classes 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 All methods in an interface are abstract, so they cannot be implemented in code and the abstract keyword is not necessary Classes can implement an interface while inheriting from another class at the same time PHP - Using Interfaces To implement an interface, a class must use the implements keyword. A class that implements an interface must implement all of the interface's methods. Example makeSound(); ?> From the example above, let's say that we would like to write software which manages a group of animals. There are actions that all of the animals can do, but each animal does it in its own way. Using interfaces, we can write some code which can work for all of the animals even if each animal behaves differently: Example makeSound(); } ?> Example Explained Cat, Dog and Mouse are all classes that implement the Animal interface, which means that all of them are able to make a sound using the makeSound() method. Because of this, we can loop through all of the animals and tell them to make a sound even if we don't know what type of animal each one is. Since the interface does not tell the classes how to implement the method, each animal can make a sound in its own way. PHP OOP - Traits PHP - What are Traits? PHP only supports single inheritance: a child class can inherit only from one single parent. So, what if a class needs to inherit multiple behaviors? OOP traits solve this problem. Traits are used to declare methods that can be used in multiple classes. Traits can have methods and abstract methods that can be used in multiple classes, and the methods can have any access modifier (public, private, or protected). Traits are declared with the trait keyword: Syntax To use a trait in a class, use the use keyword: Syntax Let's look at an example: Example msg1(); ?> Example Explained Here, we declare one trait: message1. Then, we create a class: Welcome. The class uses the trait, and all the methods in the trait will be available in the class. If other classes need to use the msg1() function, simply use the message1 trait in those classes. This reduces code duplication, because there is no need to redeclare the same method over and over again. PHP - Using Multiple Traits Let's look at another example: Example msg1(); echo "
"; $obj2 = new Welcome2(); $obj2->msg1(); $obj2->msg2(); ?> Example Explained Here, we declare two traits: message1 and message2. Then, we create two classes: Welcome and Welcome2. The first class (Welcome) uses the message1 trait, and the second class (Welcome2) uses both message1 and message2 traits (multiple traits are separated by comma). PHP OOP - Static Methods PHP - Static Methods Static methods can be called directly - without creating an instance of the class first. Static methods are declared with the static keyword: Syntax To access a static method use the class name, double colon (::), and the method name: Syntax ClassName::staticMethod(); Let's look at an example: Example Example Explained Here, we declare a static method: welcome(). Then, we call the static method by using the class name, double colon (::), and the method name (without creating an instance of the class first). PHP - More on Static Methods A class can have both static and non-static methods. A static method can be accessed from a method in the same class using the self keyword and double colon (::): Example Static methods can also be called from methods in other classes. To do this, the static method should be public: Example To call a static method from a child class, use the parent keyword inside the child class. Here, the static method can be public or protected. Example websiteName = parent::getWebsiteName(); } } $domainW3 = new domainW3; echo $domainW3 -> websiteName; ?> PHP OOP - Static Properties PHP - Static Properties Static properties can be called directly - without creating an instance of a class. Static properties are declared with the static keyword: Syntax To access a static property use the class name, double colon (::), and the property name: Syntax ClassName::staticProp; Let's look at an example: Example Example Explained Here, we declare a static property: $value. Then, we echo the value of the static property by using the class name, double colon (::), and the property name (without creating a class first). PHP - More on Static Properties A class can have both static and non-static properties. A static property can be accessed from a method in the same class using the self keyword and double colon (::): Example staticValue(); ?> To call a static property from a child class, use the parent keyword inside the child class: Example xStatic(); ?> PHP Namespaces PHP Namespaces Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task They allow the same name to be used for more than one class For example, you may have a set of classes which describe an HTML table, such as Table, Row and Cell while also having another set of classes to describe furniture, such as Table, Chair and Bed. Namespaces can be used to organize the classes into two different groups while also preventing the two classes Table and Table from being mixed up. Declaring a Namespace Namespaces are declared at the beginning of a file using the namespace keyword: Syntax Declare a namespace called Html: namespace Html; Note: A namespace declaration must be the first thing in the PHP file. The following code would be invalid: Constants, classes and functions declared in this file will belong to the Html namespace: Example Create a Table class in the Html namespace: Table '{$this->title}' has {$this->numRows} rows.

"; } } $table = new Table(); $table->title = "My table"; $table->numRows = 5; ?> message(); ?> For further organization, it is possible to have nested namespaces: Syntax Declare a namespace called Html inside a namespace called Code: namespace Code\Html; Using Namespaces Any code that follows a namespace declaration is operating inside the namespace, so classes that belong to the namespace can be instantiated without any qualifiers. To access classes from outside a namespace, the class needs to have the namespace attached to it. Example Use classes from the Html namespace: $table = new Html\Table() $row = new Html\Row(); When many classes from the same namespace are being used at the same time, it is easier to use the namespace keyword: Example Use classes from the Html namespace without the need for the Html\qualifier: namespace Html; $table = new Table(); $row = new Row(); Namespace Alias It can be useful to give a namespace or class an alias to make it easier to write. This is done with the use keyword: Example Give a namespace an alias: use Html as H; $table = new H\Table(); Example Give a class an alias: use Html\Table as T; $table = new T(); PHP Iterables PHP - What is an Iterable? An iterable is any value which can be looped through with a foreach() loop. The iterable pseudo-type was introduced in PHP 7.1, and it can be used as a data type for function arguments and function return values. PHP - Using Iterables The iterable keyword can be used as a data type of a function argument or as the return type of a function: Example Use an iterable function argument: Example Return an iterable: PHP - Creating Iterables Arrays All arrays are iterables, so any array can be used as an argument of a function that requires an iterable. Iterators Any object that implements the Iterator interface can be used as an argument of a function that requires an iterable. An iterator contains a list of items and provides methods to loop through them. It keeps a pointer to one of the elements in the list. Each item in the list should have a key which can be used to find the item. An iterator must have these methods: current() - Returns the element that the pointer is currently pointing to. It can be any data type key() Returns the key associated with the current element in the list. It can only be an integer, float, boolean or string next() Moves the pointer to the next element in the list rewind() Moves the pointer to the first element in the list valid() If the internal pointer is not pointing to any element (for example, if next() was called at the end of the list), this should return false. It returns true in any other case Example Implement the Iterator interface and use it as an iterable: items = array_values($items); } public function current() { return $this->items[$this->pointer]; } public function key() { return $this->pointer; } public function next() { $this->pointer++; } public function rewind() { $this->pointer = 0; } public function valid() { // count() indicates how many items are in the list return $this->pointer < count($this->items); } } // A function that uses iterables function printIterable(iterable $myIterable) { foreach($myIterable as $item) { echo $item; } } // Use the iterator as an iterable $iterator = new MyIterator(["a", "b", "c"]); printIterable($iterator); ?>

Comments

Popular posts from this blog

MySQL Databases PDO

PHP MySQL Use The ORDER BY Clause Select and Order Data From a MySQL Database The ORDER BY clause is used to sort the result-set in ascending or descending order. The ORDER BY clause sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword. SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC To learn more about SQL, please visit our SQL tutorial. Select and Order Data With MySQLi The following example selects the id, firstname and lastname columns from the MyGuests table. The records will be ordered by the lastname column: Example (MySQLi Object-oriented) connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "id: " . $row["id"].

PHP - AJAX

PHP - AJAX Introduction AJAX is about updating parts of a web page, without reloading the whole page. What is AJAX? AJAX = Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, (which do not use AJAX) must reload the entire page if the content should change. Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs. How AJAX Works AJAX AJAX is Based on Internet Standards AJAX is based on internet standards, and uses a combination of: XMLHttpRequest object (to exchange data asynchronously with a server) JavaScript/DOM (to display/interact with the information) CSS (to style the data) XML (often used as the format for transferring data) AJAX applications are browse