Object-oriented programming in PHP

We can imagine that the universe was made up of different objects like the sun, the moon, the earth, and so on. In the same way, you can imagine a car made of different objects like wheel, rudder, gear shift ... In such a way, concepts in object-oriented programming assume that everything is like an object and deploying a software by using different objects.

We can imagine that the universe was made up of different objects like the sun, the moon, the earth, and so on. In the same way, you can imagine a car made of different objects like wheel, chassis, engine, gear shift . In such a way, concepts in object-oriented programming assume that everything is like an object and deploying a software by using different objects . You can refer to the way Steve Jobs defines object-oriented programming to make the world admire, describing an extremely easy-to-understand object-oriented programming process.

Object-oriented concepts in PHP

Before going into detail, we recall some concepts related to Object-Oriented Programming.

Class - This is a data type defined by the programmer, which includes local functions as well as local data. You can think of a Class as a Template to create multiple instances of the same type (or class) of the object.

Object - A separate instance of the data structure defined by a Class. Once you define a Class, and then create that Class Object. Objects are also known as Instances.

Member variable - These are variables defined inside a Class. This data will not be visible to the peripheral of that class and can be accessed through member functions. These variables are called attributes of the object once the object has been created.

Member functions - This is a function defined inside a Class and used to access object data.

Inheritance - When a class is defined by inheriting an existing function of a parent class, it is called inheritance. Here, the subclass will inherit all or some of the functions and member variables of the parent class.

Parent class - A class that inherits from another class. It is also called a base class (base class) or super class.

Subclass - A class that inherits from another class. It is also called a subclass or a derived class.

Polymorphism - This is an object-oriented concept that the same function can be used for different purposes. For example, the function name will still be the same, but it takes different number of parameters and can perform different tasks.

Overloading - A polymorphic type, in which some or all operators have different implementations depending on the type of their parameters. Similarly, functions can also be overloaded with different implementers.

Data abstraction - Any representation of data in which details of the implementer are hidden.

Closure - Concerning a concept we can encapsulate all data and member functions together to form an Object.

Constructor - Concerts a special function type that will be called automatically whenever there is an object creation from a Class.

Destructor - Concerts a special function type that will be called automatically whenever an object is deleted or out of scope.

Class definition in PHP

The general form for defining a new class in PHP is as follows:

  php class phpClass { var $var1 ; var $var2 = "Một hằng số" ; function myfunc ( $arg1 , $arg2 ) { [.] } [.] } ?> 

Below is an explanation of each line above:

  1. The special class procedure comes with the name of the class you want to define.
  2. Brace brackets surround any number of variable declarations or function definitions.
  3. Variable declarations start with the special procedure var that comes with a convention variable name; they can also have an initial assignment to a constant value.
  4. The function definition here is quite similar to the standalone functions in PHP, but this is a local function for the class and will be used to set and access object data.

For example:

The following example defines a class named Books.

Part 1:

  php class Books { /* các biến thành viên */ var $price ; var $title ; /* các hàm thành viên */ function setPrice ( $par ){ $this -> price = $par ; } function getPrice (){ echo $this -> price . "
" ; } function setTitle ( $par ){ $this -> title = $par ; } function getTitle (){ echo $this -> title . "
" ; } } ?>

The variable $ this is a special variable and it references the same object (eg itself).

Create Object in PHP

Once you have defined your class, you can create as many objects as you like. The following example is how to create an object using the new keyword in PHP.

Part 2:

 $ tieng Anh = new Books; 
$ toanCaoCap = new Books;
$ tuTuongHCM = new Books;

Here, we have created 3 objects and these objects are independent of each other and they will have separate existence. In the next section, we see how to access member functions and handle member variables in PHP.

Call member functions in PHP

After creating the objects, you will be able to call member functions related to that object. A member function will only be able to handle member variables related to that object.

The following example illustrates how to set the title and price for 3 books by calling member functions.

Part 3:

 $tiengAnh -> setTitle ( "English Grammar in Use" ); $tuTuongHCM -> setTitle ( "Toán cao cấp 1" ); $toanCaoCap -> setTitle ( "Tư tưởng Hồ Chí Minh" ); $tiengAnh -> setPrice ( 10 ); $tuTuongHCM -> setPrice ( 15 ); $toanCaoCap -> setPrice ( 7 ); 

Now call other member functions to get the value set in the above example:

Part 4:

 $tiengAnh -> getTitle (); $tuTuongHCM -> getTitle (); $toanCaoCap -> getTitle (); $tiengAnh -> getPrice (); $tuTuongHCM -> getPrice (); $toanCaoCap -> getPrice (); 

Save the above 4 sections of code (in the order above) in a file named test.php in htdocs , then open the browser and type in the address http:/// localhost: 8080 / test.php will result:

Object-oriented programming in PHP Picture 1Object-oriented programming in PHP Picture 1

The constructor function in PHP

The constructor function is a special type of function that will be called automatically whenever there is an object creation from a Class. Therefore, we take advantage of this operation, by creating many things through constructor functions in PHP.

PHP provides a special function called __construct () to define a constructor. You can pass as many parameters as you want into this constructor.

The following example will create a constructor for Books class and it will initialize price and title for book at the time of creating this object.

Part 1.1:

 function __construct ($ par1, $ par2) { 
$ this-> price = $ par1;
$ this-> title = $ par2;
}

Now, we don't need to call separate function sets to set prices and titles. We can only initialize their two member variables at the time of creating the object. You check the following example:

Part 2.2:

 $tiengAnh = new Books ( "English Grammar in Use" , 10 ); $toanCaoCap = new Books ( "Toán cao cấp 1" , 15 ); $tuTuongHCM = new Books ( "Tư tưởng Hồ Chí Minh" , 7 ); /* lấy các giá trị đã được thiết lập */ $tiengAnh -> getTitle (); $tuTuongHCM -> getTitle (); $toanCaoCap -> getTitle (); $tiengAnh -> getPrice (); $tuTuongHCM -> getPrice (); $toanCaoCap -> getPrice (); 

Set the contructor (section 1.1) to the class (part 1) and then replace sections 2, 3 and 4 with part 2.2 (in the order above) in a file named test.php in htdocs , then open the browser and type the address http:/// localhost: 8080 / test.php will give the same result as above:

Object-oriented programming in PHP Picture 2Object-oriented programming in PHP Picture 2

Destructor in PHP

Like a constructor function in PHP, you can define a destructor function using the __destruct () function. You can free all sources with a destructor in PHP.

Calculate inheritance in PHP

PHP class definitions can inherit from a parent class definition using the extends clause in PHP. Its syntax is as follows:

 class Child extends Parent { 

}

The effect of inheritance is subclass (subclass or inheritance) with the following characteristics:

Automatically have all member variable declarations of parent class.

Automatically have all member functions like in the parent class, which (by default) will work in the same method as when the function does in the parent class.

The following example inherits the Books class and adds some features as required.

 class Novel extends Books { var publisher ; function setPublisher ( $par ){ $this -> publisher = $par ; } function getPublisher (){ echo $this -> publisher . "
" ; } }

Now, in addition to the inherited functions, the Novel class adds two member functions.

Override function (Function Overriding) in PHP

Function definitions in subclasses override the definitions with the same name in the parent classes. In a subclass, we can modify the definition of a function inherited from the parent class.

In the following example, the getPrice and getTitle functions are overwritten to return the values.

 function getPrice (){ echo $this -> price . "
" ; return $this -> price ; } function getTitle (){ echo $this -> title . "
" ; return $this -> title ; }

Member public in PHP

Unless you specify, otherwise the properties (property) and the method of a class are public. That is, they can be accessed in the following three situations:

From outside the class in which it is declared.

From inside the class in which it is declared.

From within the external class that implements that class in which it is declared.

So far, we have seen all members are public members. If you want to limit the access of members of a class, then you define the class member as private or protected in PHP.

Private member in PHP

By specifying a member as private, you restrict access to the class in which it is declared. Private members cannot be referenced from classes that inherit the class in which they are declared and cannot be accessed from outside the class.

A class member can be specified as private by using the private keyword in front of the member.

 class MyClass { private $car = "skoda" ; $driver = "SRK" ; function __construct ( $par ) { // các lệnh ở đây được thực thi mỗi khi // một instance của class // được tạo } function myPublicFunction () { return ( "Đây là một hàm Public!" ); } private function myPrivateFunction () { return ( "Đây là một hàm Private!" ); } } 

When the MyClass class is inherited by another class by using extends, the function myPublicFunction () will be visible, like $ driver. The inheritance class will not recognize or access the function myPrivateFunction and $ car, because they are declared private.

Protected member in PHP

A protected property or method is accessible in the class in which it is declared, as well as in classes that inherit from that class. Protected members are not available with the periphery of these two types of classes. A class member can be designated protected by using the protected keyword before that member in PHP.

Here is another version of MyClass:

 class MyClass { protected $car = "skoda" ; $driver = "SRK" ; function __construct ( $par ) { // các lệnh ở đây được thực thi mỗi khi // một instance của class // được tạo } function myPublicFunction () { return ( "Đây là một hàm Public!" ); } protected function myPrivateFunction () { return ( "Đây là một hàm Protected!" ); } } 

Interface in PHP

Interface is defined to provide a generic function name for implementers. Different implementors can deploy their interfaces according to their requirements. You can say, Interface is a framework that is implemented by the programmer.

As in PHP 5, it is possible to define an Interface, like:

 interface Mail { public function sendMail (); } 

Then, if another class implements that Interface, it's like:

 class Report implements Mail { // lớp này cần định nghĩa hàm sendMail() } 

Constant (Constant) in PHP

A constant is something like a variable in which it holds a value, but it is actually more like a function, because a constant is irreversible. Once you declare a constant, it does not change.

Declaring a constant in PHP is quite easy, as done in this version of MyClass.

 class MyClass { const requiredMargin = 1.7 ; // từ khóa const function __construct ( $incomingValue ) { // các lệnh ở đây được thực thi mỗi khi // một instance của class // được tạo } } 

In this class, requireMargin is a constant. It is declared with the const keyword in PHP, and its value will not change in any situation. Remember, the constant name does not start with $, as in the variable name.

Abstract class (Abstract Class) in PHP

An abstract class is a class that cannot be initialized, only inherited. You declare an abstract class with the abstract keyword in PHP, as shown below.

When inheriting from an abstract class, all methods marked abstract in the parent class declaration must be defined by the subclass; In addition, these methods must be defined with the same visibility.

 abstract class MyAbstractClass { abstract function myAbstractFunction () { } } 

Note that function definitions within an abstract class must also be preceded by the abstract keyword. In PHP, it is not valid if you have defined the abstract function inside a non-abstract class.

Static keyword in PHP

Declaring class members or class methods is static making them accessible without a class initialization. A member declared as static cannot be accessed with a class object that has been initialized (although a method is static can).

Try the following example:

  php class Foo { public static $my_static = 'foo' ; public function staticValue () { return self :: $my_static ; } } print Foo :: $my_static . "n" ; $foo = new Foo (); print $foo -> staticValue () . "n" ; ?> 

Final keyword in PHP

PHP 5 introduces the final keyword, which prevents subclasses from overwriting a method by prefixing the keyword definition final. If the class itself is declared final, it cannot be inherited.

The following example creates Fatal Error: Cannot override final method BaseClass :: moreTesting ()

  php class BaseClass { public function test () { echo "BaseClass::test() called
" ; } final public function moreTesting () { echo "BaseClass::moreTesting() called
" ; } } class ChildClass extends BaseClass { public function moreTesting () { echo "ChildClass::moreTesting() called
" ; } } ?>

Call the parent constructor in PHP

Instead of writing a new constructor for the subclass, you can write it by calling the parent class constructor explicitly and then doing whatever it takes to initialize this subclass. Here is a simple example in PHP.

 class Name { var $_firstName ; var $_lastName ; function Name ( $first_name , $last_name ) { $this -> _firstName = $first_name ; $this -> _lastName = $last_name ; } function toString () { return ( $this -> _lastName . ", " . $this -> _firstName ); } } class NameSub1 extends Name { var $_middleInitial ; function NameSub1 ( $first_name , $middle_initial , $last_name ) { Name :: Name ( $first_name , $last_name ); $this -> _middleInitial = $middle_initial ; } function toString () { return ( Name :: toString () . " " . $this -> _middleInitial ); } } 

In this example, we have the Name parent class, have a constructor that takes two parameters, and a NameSub1 subclass, which has a constructor that takes three parameters. NameSub1's Constructor functions by calling its parent constructor explicitly using the syntax :: (passing its two parameters) and then setting an additional field. In the same way, NameSub1 defines the toString () function which overrides the parent class.

Example - A constructor can be defined with the same name as the name of a class, as in the example above.

Follow tutorialspoint

Previous article: PHP & XML

Next lesson: PHP for Programmer C

5 ★ | 1 Vote