Php oop classes and objects, php: object oriented programming

Introduction

Object-oriented programming is an approach khổng lồ programming where objects và classes are used. Now-a-days Java và C++ are mostly used for object-oriented programming. There was limited scope of object-oriented programming in PHP 4, but in PHP 5, the object model was rewritten for better performance và more features. Now PHP 5 has a full object model.


What is an object?

The fundamental idea behind an object-oriented language is to lớn enclosea bundle of variables and functions into a single unit & keep both variables và functions safe from outside interference & misuse.Such a unit is called object which acts on data.The mechanism that binds together data và functions are called encapsulation. This feature makes it easy lớn reuse code in various projects. The functions declared in an objectprovides the way khổng lồ access the data. The functions of an object are called methods & all the methods of an object have access to lớn variables called properties.The following picture shows thecomponents of an object.

*

Class

In object-oriented programming, a class is a construct or prototype from which objects are created. A class defines constituent members which enable class instances lớn have state and behavior. Data field members enable a class object to maintain state and methods enable a class object"s behavior. The following picture shows the components of a class.

Bạn đang xem: Php oop classes and objects, php: object oriented programming

*

PHP: Creating classes và Instantiation

The class definition starts with the từ khóa class followed by a class name, then followed by a phối of curly braces () which enclose constants, variables (called "properties"), và functions (called "methods") belonging lớn the class.A valid class name (excluding the reserved words) starts with a letter or underscore, followed by any number of letters, numbers, or underscores.Class names usually begin with an uppercase letter lớn distinguish them from other identifiers.An instance is an object that has been created from an existing class.Creating an object from an existing class is called instantiating the object.To create an object out of a class, the new keyword must be used.Classes should be defined prior lớn instantiation.

Example:

In the following example keyword new is used to lớn instantiate an object. Here $myobj represents an object of the class Myclass.

Let see the contents of the class Myclass using var_dump() function (display structured information (type & value) about one or more variables):

Output:

object(Myclass)#1 (0) View the example in the browser

Setting Properties

Class member variables are called properties. Sometimes they are referred as attributes or fields.The properties hold specific data and related with the class in which it has been defined.Declaring a property in a class is an easy task, use one of the từ khóa public, protected, or private followed by a normal variable declaration.If declared using var (compatibility with PHP 4), the property will be defined as public.public : The property can be accessed from outside the class, either bythe script or from another classprivate : No access is granted from outside the class, either by thescript or from another class.protected : No access is granted from outside the class except aclass that’s a child of the class with the protected property or method.nowdocs ( as of PHP 5.3.0) can be used in any static data context, including property declarations.

Example:

After an object is instantiated, you can access the property of a class using the object-> operator. Any thành viên declared with từ khoá "private" or "protected" cannot be accessed outside the method of the class.

font_size;?>Output:

10View the example in the browser

Note: There is a common mistake to use more than one dollar sign when accessing variables. In the above example there will be no $ sign before font_size (echo $f->font_size).

After defining methods we will discuss an example with public, private & protected class properties.

Setting Methods

The functions which are declared in a class are called methods.A class method is exactly similar lớn PHP functions.Declaring a method in a class is an easy task, use one of the từ khoá public, protected, or private followed by a method name.public : The method can be accessed from outside the class.private : No access is granted from outside the class.protected : No access is granted from outside the class except a class that’s a child of the class with the protected property or method.A valid method name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.The method body toàn thân enclosed within a pair of braces which contains codes. The opening curly brace ( ) indicates the beginning of the method code and the closing curly ( ) brace indicates the termination of the method.If the method is not defined by public, protected, or private then default is public. Can access properties và methods of the current instance using $this (Format $this->property) for non static property.

Example:

After an object is instantiated, you can access the method of a class using the object & -> operator. In the following example customize_print() method will print a string with a specific font kích thước and color within a html paragraph element with the help of php echo statement.

font_size.";color:".$this->font_color.";>".$this->string_name."

"; }}$f = new MyClass;echo $f->customize_print();?>

Output:

*

View the example in the browser

Now change the value of font_size, font_color and the string and check what the method custimize_print() returns.

Xem thêm: How To Fix "Aw Snap" On Chrome, “Aw Snap!” Crash Makes A Comeback In Chrome 79

font_size.";color:".$this->font_color.";>".$this->string_name."

"; }}$f = new MyClass;$f->font_size = "20px";$f->font_color = "red";$f->string_name = "Object Oriented Programming";echo $f->customize_print();?>

Output:

View the example in the browser

PHP: Scope Resolution Operator (::)

In PHP, the scope resolution operator is also called Paamayim Nekudotayim which means "double colon" or "double dot twice" in Hebrew. The double colon (::), is a token which allows access to lớn static, constant, and overridden properties or methods of a class.

PHP: Class Constants

A special entity that remains fixed on an individual class basis. Constant names are not preceded by a dollar sign ($) like a normal variable declaration.Interfaces may also include constants. When calling a class constant using the $classname :: constant syntax, the classname can actually be a variable. As of PHP 5.3, you can access a static class constant using a variable reference (Example: className :: $varConstant).

Define & using a constant

"; } } echo MyClass::constant1 . ""; $classname = "MyClass"; echo $classname::constant1 . ""; // As of PHP 5.3.0 $class = new MyClass(); $class->PrintConstant(); echo $class::constant1.""; // As of PHP 5.3.0 ?>Understanding public, private, protected properties

Properties can be public, private or protected. Public means that properties can be accessed everywhere, private means properties can be accessed by the class that defines the thành viên and protected means properties can be accessed only within the class itself và by inherited & parent classes.

Example:

font_size; echo $this->font_color; echo $this->string_name; }}$obj = new MyClass;echo $obj->font_size; //Display 18px echo $obj->font_color; //Fatal error: Cannot access private property Myclass::$font_color in F:wamp..echo $obj->string_name; //Fatal error: Cannot access protected property Myclass::$string_name in F:wamp.. $obj->property_print(); //Display 18pxblueobatambeienwasirherbal.com?>Understanding public, private, protected methods

Methods can be public, private or protected. Public means that methods can be accessed everywhere, private means methods can be accessed by the class that defines the thành viên and protected means methods can be accessed only within the class itself và by inherited & parent classes.

public function my_public_method() echo "This is a Public method"; private function my_private_method() echo "This is a Private method"; protected function my_protected_method() echo "This is a Protected method"; // This is public function test() $this->my_public_method(); $this->my_private_method(); $this->my_protected_method(); } $obj = new MyClass; $obj->my_public_method(); //Display This is a Public method $obj->my_private_method();//Fatal error: điện thoại tư vấn to private method Myclass::my_private_method() from context "" in F:wampwww.. $obj>my_protected_method();//Fatal error: gọi to undefined function my_protected_method() in F:wampwww.. $obj->test(); //Display This is a Public methodThis is a Private methodThis is a Protected method?>Note: PHP uses inheritance in it"s object model and when you extend a class, the subclass inherits all of the public and protected methods from the parent class. When we will discuss the inheritance, you will get more information about protected properties & methods.

PHP Constructor methods

The constructor is a special built-in method, added with PHP 5, allows developers to declare for classes. Constructors allow lớn initializing object properties ( i.e. The values of properties) when an object is created.Classes which have a constructor method execute automatically when an object is created. The "construct" method starts with two underscores (__). The constructor is not required if you don"t want lớn pass any property values or perform any actions when the object is created. PHP only ever calls one constructor.

The general syntax for constructor declaration follows :

function __construct()/* Class initialization code */The type of argument1, argument2,.......,argumentN are mixed.

Example:

font_size = $font_size; $this->font_color = $font_color; $this->string_value = $string_value; }// Declare a method for customize print function customize_print() echo "font_size.";color:".$this->font_color.";>".$this->string_value."

"; }// Create a new object and passes three parameters $f = new MyClass("20px","red","Object Oriented Programming");// điện thoại tư vấn the method lớn display the string echo $f->customize_print(); ?>

Output:

View the example in the browser

More example on constructors:

Like properties, constructors can call class methods or other functions. In the following example there is no need to gọi the method separately (after creating the object & passing the parameters, see the previous example) as it is already declared within the constructor. See the following example :

font_size = $font_size; $this->font_color = $font_color; $this->string_value = $string_value; $this->customize_print(); }// Declare a method for customize print function customize_print() echo "font_size.";color:".$this->font_color.";>".$this->string_value."

"; }// Create a new object & passes three parameters $f = new MyClass("20px","red","Object Oriented Programming"); ?>

Output:

View the example in the browser

PHP Destructors methods

The destructor is the counterpart of constructor. A destructor function is called when the object is destroyed A destructor function cleans up any resources allocated khổng lồ an object after the object is destroyed.A destructor function is commonly called in two ways: When a script ends or manually delete an object with the unset() function The "destructor" method starts with two underscores (__).

The general syntax for destructor declaration follows :

function __destruct /* Class initialization code */The type of argument1, argument2,.......,argumentN are mixed.

Example:

"; $this->name = "MyClass"; } function __destruct() echo "Destroying " . $this->name . ""; }$obj = new MyClass();?>Output:

obatambeienwasirherbal.comDestroying MyClassView the example in the browser

PHP: Using multiple instances of the same class

In the following example we have created multiple objects (instances) of the same class và passes different values.

font_size = $font_size; $this->font_color = $font_color; $this->string_value = $string_value; $this->customize_print(); }// Declare a method for customize print function customize_print() echo "font_size.";color:".$this->font_color.";>".$this->string_value."

"; }// Create first object & passes three parameters $a = new MyClass("30px","red","Object Oriented Programming");// Create second object and passes three parameters $b = new MyClass("25px","blue","Object Oriented Programming");// Create third object & passes three parameters $c = new MyClass("20px","green","Object Oriented Programming");// Create fourth object và passes three parameters $d = new MyClass("15px","black","Object Oriented Programming"); ?>

Output:

*

View the example in the browser

PHP : spl_autoload_register()

Many developers writing object-oriented applications create one PHP source tệp tin per class definition. One of the biggest annoyances is having khổng lồ write a long danh mục of needed includes at the beginning of each script (one for each class). Traditionally __autoload() function was used to automatically load classes. As of PHP 5.1.2 a new function spl_autoload_register() is introduced which provides a more flexible alternative for autoloading classes. For this reason, using __autoload() is discouraged and may be deprecated or removed in the future.