IntroductionObject-oriented programming is an approach to programming where objects and classes are used. Now-a-days Java and 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 and more features. Now PHP 5 has a full object model. Show What is an object? The fundamental idea behind an object-oriented language is to enclose a bundle of variables and functions into a single unit and keep both variables and functions safe from outside interference and misuse. Such a unit is called object which acts on data. The mechanism that binds together data and functions are called encapsulation. This feature makes it
easy to reuse code in various projects. The functions declared in an object provides the way to access the data. The functions of an object are called methods and all the methods of an object have access to variables called properties. 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 to 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. PHP: Creating classes and Instantiation
Example:
In the following example keyword new is used to 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 and value) about one or more variables):
Output: object(Myclass)#1 (0) { } View the example in the browser Setting Properties
Example: After an object is instantiated, you can access the property of a class using the object and -> operator. Any member declared with keyword "private" or "protected" cannot be accessed outside the method of the class.
Output: 10 View 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 and protected class properties. Setting Methods
Example: After an object is instantiated, you can access the method of a class using the object and -> operator. In the following example customize_print() method will print a string with a specific font size and color within a html paragraph element with the help of php echo statement.
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.
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 static, constant, and overridden properties or methods of a class. PHP: Class Constants
Define and using a constant
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 member and protected means properties can be accessed only within the class itself and by inherited and parent classes. Example:
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 member and protected means methods can be accessed only within the class itself and by inherited and parent classes.
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 and methods. PHP Constructor methods
The general syntax for constructor declaration follows : function __construct([argument1, argument2, ..., argumentN]) Example:
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 call the method separately (after creating the object and passing the parameters, see the previous example) as it is already declared within the constructor. See the following example :
Output: View the example in the browser PHP Destructors methods
The general syntax for destructor declaration follows : function __destruct
Example:
Output: w3resource Destroying MyClass View 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 and passes different values.
Output: View the example in the browser PHP : spl_autoload_register() 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). 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. Syntax: bool spl_autoload_register ([ callable $autoload_function [, bool $throw = true [, bool $prepend = false ]]] ) Parameter
Return values Returns TRUE on success or FALSE on failure. You can use spl_autoload_register() function in following way :
Example: At first we will create two classes and store them in /php/classes-objects/resource path: class1.php
class2.php
Now, create a file printstring.php and save it in /php/classes-objects :
In the above example we are trying to create two objects, where class names 'class1' (save in /php/classes-objects/resource/class1.php) and 'class2' (save in /php/classes-objects/resource/class2.php). PHP passes this name as a string to spl_autoload_register(), which allows you to pick up the variable and use it to "include" the appropriate class/file. Output: View the example in the browser PHP: Inheritance
Example: In the following example subclass, 'Mysubclass' inherits all the protected properties and public method from 'Myclass' class. In addition, we add a text-decoration attribute within echo statement in the subclass 'Mysubclass'.
Output: View the example in the browser PHP: Interfaces
Syntax: interface MyInterface { function method1(); function method2(); } class MyClass implements MyInterface { function method1() { // definition of method1 } function method2() { // definition of method2 } } PHP: Object Cloning
Example: In PHP object cloning is done using clone keyword. Here is an example of object cloning : Example: Object cloning with magic method __clone
Output: object(MyClass)#1 (2) { ["x"]=> string(10) "w3resource" ["y":"MyClass":private]=> string(3) "com" } object(MyClass)#2 (2) { ["x"]=> string(1) "z" ["y":"MyClass":private]=> string(3) "com" } View the example in the browser PHP: Magic methods The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state() and __clone() are magical in PHP classes. PHP reserves all function names starting with __ as magical. We have already discussed __construct(), __destruct() and __clone() methods. Here are other magic methods : __call() __call() is triggered when invoking inaccessible methods in an object context. Syntax : public mixed __call ( string $name , array $arguments ) __callStatic() __callStatic() is triggered when invoking inaccessible methods in a static context. Syntax : public mixed __call ( string $name , array $arguments ) __get() __get() is utilized for reading data from inaccessible properties. Syntax : public mixed __get ( string $name ) __set() __set() is run when writing data to inaccessible properties. Syntax : public void __set ( string $name , mixed $value ) __isset() __isset() is triggered by calling isset() or empty() on inaccessible properties. Syntax : public bool __isset ( string $name ) __unset() __unset() is invoked when unset() is used on inaccessible properties. Syntax : public void __unset ( string $name ) __sleep() __sleep() is used to commit pending data or perform similar cleanup tasks. Also, the function is useful if you have very large objects which do not need to be saved completely. Syntax : public array __sleep ( void ) __wakeup() __wakeup() is used to reestablish any database connections that may have been lost during serialization and perform other reinitialization tasks. Syntax : void __wakeup ( void ) __toString() The __toString() method allows a class to decide how it will react when it is treated like a string. Syntax : public string __toString ( void ) __invoke() The __invoke() method is called when a script tries to call an object as a function. Syntax : mixed __invoke ([ $... ] ) __set_state() This static method is called for classes exported by var_export() since PHP 5.1.0. Syntax : static object __set_state ( array $properties ) We will provide some examples of magic methods soon. Previous: PHP User Define Function How do you define a class in PHP?Class is a programmer-defined data type, which includes local methods and local variables. Class is a collection of objects. Object has properties and behavior.
Can we create class in PHP?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.
How do I declare an object in PHP?php $name="Deepak"; $age=21; $percent=75.50; $obj1=(object)$name; print_r($obj1); $obj2=(object)$age; print_r($obj2); $obj3=(object)$percent; print_r($obj3); ?>
How do you declare a class syntax?In general, class declarations can include these components, in order:. Modifiers such as public, private, and a number of others that you will encounter later. ... . The class name, with the initial letter capitalized by convention.. The name of the class's parent (superclass), if any, preceded by the keyword extends.. |