PHP Object Oriented Programming CLASS OBJECT AND METHOD
PHP Object Oriented Programming
CLASS, OBJECT AND METHOD Object-oriented programming is an approach to programming where objects and classes are used.
OBJECT An entity that has state and behavior is known as an object Example. dog, chair, bike, marker, pen, table, car etc. 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. If we consider a dog, state is - name, breed, color, behavior is - barking, running
If you compare the software object with a real world object, they have very similar characteristics. Software objects also have a state and behavior. A software object's state is stored in fields (data members) and behavior is shown via methods To declare and create an object you use the syntax object_name = new class_name (arguments);
CLASS A class is a group of objects that has common properties. It is a template or blueprint from which objects are created. So object is the instance(result) of a 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 behaviour. Data field members enable a class object to maintain state and methods enable a class object's behaviour. A class can contain: data member method constructor class and interface
SYNTAX TO DECLARE A CLASS: class <class_name> { data member; method; } Class Names - For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case. Example: class My. First. Php. Class
<? php class Myclass { // Add property statements here // Add the methods here } $myobj = new My. Class; var_dump($myobj); ? > Note: Using var_dump() function (display structured information (type and value) about one or more variables): Output: object(Myclass)#1 (0) { }
PHP OOPS CONCEPTS Object Class Inheritance Polymorphism Abstraction Encapsulation
OOPS CONCEPTS Object Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical. Class Collection of objects is called class. It is a logical entity. Inheritance When one object acquires all the properties and behaviours of parent object i. e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
OOPS CONCEPTS Polymorphism When one task is performed by different ways i. e. known as polymorphism. For example: to convince the customer differently, to draw something e. g. shape or rectangle etc. .
OOPS CONCEPTS Abstraction Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing. Encapsulation Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines.
ADVANTAGE OF OOPS OVER PROCEDUREORIENTED PROGRAMMING LANGUAGE OOPs makes development and maintenance easier where as in Procedure-oriented programming language it is not easy to manage if code grows as project size grows. OOPs provides data hiding whereas in Procedure-oriented programming language a global data can be accessed from anywhere. OOPs provides ability to simulate real-world event much more effectively. We can provide the solution of real word problem if we are using the Object-Oriented Programming language.
STATIC The static keyword in PHP is used for memory management mainly. We can apply static keyword with variables, methods. The static keyword belongs to the class than instance of the class (object). The static can be: variable (also known as class variable) method (also known as class method)
If you declare any variable as static, it is known static variable. The static variable can be used to refer the common property of all objects (that is not unique for each object) e. g. company name of employees, college name of students etc. The static variable gets memory only once in class area at the time of class loading. Advantage of static variable It makes your program memory efficient (i. e it saves memory).
THIS KEYWORD There can be a lot of usage of $this keyword. In php, $this is a reference variable that refers to the current object. Here is given the 6 usage of php this keyword can be used to refer current class instance variable. this() can be used to invoke current class constructor. this keyword can be used to invoke current class method (implicitly) this can be passed as an argument in the method call. this can be passed as argument in the constructor call. this keyword can also be used to return the current class instance.
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. public : The property can be accessed from outside the class, either by the script or from another class private : No access is granted from outside the class, either by the script or from another 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.
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. <? php class Myclass { public $font_size =10; } $f = new My. Class; echo $f->font_size; ? > Output: 10
A SAMPLE OF A CLASS IS GIVEN BELOW: class Dog { $breed; $age; $color; void barking() { } void hungry() { } void sleeping() { } } • Method Names - All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example: public void my. Method. Name()
SETTING METHODS In PHP, a method is like function (i. e. ) used to expose behaviour of an object. The functions which are declared in a class are called methods. A class method is exactly similar to PHP functions. Declaring a method in a class is an easy task, use one of the keyword 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 the class with the protected property or method. a class that’s a child of The method body 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 and methods of the current instance using $this (Format $this->property) for non static property. Advantage of Method Code Reusability Code Optimization
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. <? php class Myclass { public $font_size ="18 px"; public $font_color = "blue"; public $string_name = “SRM"; public function customize_print() { echo "<p style=font-size: ". $this->font_size. "; color: ". $this->font_color. "; >". >string_name. "</p>"; } } $f = new My. Class; echo $f->customize_print(); ? > $this-
Now change the value of font_size, font_color and the string and check what the method custimize_print() returns. <? php class Myclass { public $font_size ="18 px"; public $font_color = "blue"; public $string_name = “SRM"; public function customize_print() { echo "<p style=font-size: ". $this->font_size. "; color: ". $this->font_color. "; >". $this>string_name. "</p>"; }} $f = new My. Class; $f->font_size = "20 px"; $f->font_color = "red"; $f->string_name = "Object Oriented Programming"; echo $f->customize_print(); ? > Output: Object Oriented Programming
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. When referencing these items from outside the class definition, use the name of the class. As of PHP 5. 3. 0, it's possible to reference the class using a variable. The variable's value can not be a keyword. (e. g. self, parent and static).
SCOPE RESOLUTION OPERATOR (: : ) Example #1 : : from outside the class definition <? php class My. Class { const CONST_VALUE = 'A constant value'; } $classname = 'My. Class'; echo $classname: : CONST_VALUE; // As of PHP 5. 3. 0 echo My. Class: : CONST_VALUE; ? >
Three special keywords self, parent and static are used to access properties or methods from inside the class definition. Example #2 : : from inside the class definition <? php class Other. Class extends My. Class { public static $my_static = 'static var'; public static function double. Colon() { echo parent: : CONST_VALUE. "n"; echo self: : $my_static. "n"; }} $classname = 'Other. Class'; $classname: : double. Colon(); // As of PHP 5. 3. 0 Other. Class: : double. Colon(); ? >
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: class. Name : : $var. Constant).
DEFINE AND USING A CONSTANT <? php class My. Class { constant 1 = 'PHP Class Constant'; function Print. Constant() { echo self: : constant 1. " "; } } echo My. Class: : constant 1. " "; $classname = "My. Class"; //reference echo $classname: : constant 1. " "; // As of PHP 5. 3. 0 $class = new My. Class(); //object $class->Print. Constant(); echo $class: : constant 1. " "; // As of PHP 5. 3. 0 ? >
EXAMPLE 2: <? php class My. Class { const CONSTANT = 'constant value'; function show. Constant() { echo self: : CONSTANT. "n"; } } echo My. Class: : CONSTANT. "n"; $classname = "My. Class"; echo $classname: : CONSTANT. "n"; // As of PHP 5. 3. 0 $class = new My. Class(); $class->show. Constant(); echo $class: : CONSTANT. "n"; // 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 member and protected means properties can be accessed only within the class itself and by inherited and parent classes.
EXAMPLE: <? php // Define a class Myclass { // Declare $font_size as Public property public $font_size ="18 px"; // Declare $font_color as Private property private $font_color = "blue"; // Declare $string_name as Protected property protected $string_name = “SRM"; // Declare a method to print properties value. This is public. function property_print() { echo $this->font_size; echo $this->font_color; cho $this->string_name; }} $obj = new My. Class; echo $obj->font_size; //Display 18 px 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 18 pxbluew 3 resource ? >
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.
<? php // Define a class Myclass { // Declare a public method 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 My. Class; $obj->my_public_method(); //Display This is a Public method $obj->my_private_method(); //Fatal error: Call to private method Myclass: : my_private_method() from context '' in F: wampwww. . $obj>my_protected_method(); //Fatal error: Call to undefined function my_protected_method() in F: wampwww. . obj->test(); //Display This is a Public method. This is a Private method. This 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 and methods.
PHP CONSTRUCTOR METHODS Constructor in PHP is a special type of method that is used to initialize the object. PHP constructor is invoked at the time of object creation. It constructs the values i. e. provides data for the object that is why it is known as constructor. The constructor is a special built-in method, added with PHP 5, allows developers to declare for classes. Constructors allow to 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 to pass any property values or perform any actions when the object is created. PHP only ever calls one constructor.
CONSTRUCTOR Rules for creating PHP constructor There are basically two rules defined for the constructor. Constructor name must be same as its class name or __construct keyword Types of PHP constructors There are two types of constructors: Default constructor (no-arg constructor) Parameterized constructor The general syntax for constructor declaration follows : function __construct([argument 1, argument 2, . . . , argument. N]) { /* Class initialization code */ } The type of argument 1, argument 2, . . . . , argument. N are mixed.
EXAMPLE: <? php // Define a class Myclass { // Declaring three private varaibles private $font_size; private $font_color; private $string_value; // Declarte construct method which accepts three parameters function __construct($font_size, $font_color, $string_value) { $this->font_size = $font_size; $this->font_color = $font_color; $this->string_value = $string_value; } // Declare a method for customize print function customize_print() { echo "<p style=font-size: ". $this->font_size. "; color: ". $this->font_color. "; >". $this->string_value. "</p>"; } } // Create a new object and passes three parameters $f = new My. Class('20 px', 'red', 'Object Oriented Programming'); // Call the method to display the string echo $f->customize_print(); ? > Output: Object Oriented Programming
CONSTRUCTOR OVERLOADING Constructor overloading is a technique in PHP in which a class can have any number of constructors that differ in parameter lists.
CONSTRUCTOR OVERLOADING <? php class Base. Class { function __construct() { print "In Base. Class constructorn"; } } class Sub. Class extends Base. Class { function __construct() { parent: : __construct(); print "In Sub. Class constructorn"; } } class Other. Sub. Class extends Base. Class { // inherits Base. Class's constructor }
// In Base. Class constructor $obj = new Base. Class(); // In Base. Class constructor // In Sub. Class constructor $obj = new Sub. Class(); // In Base. Class constructor $obj = new Other. Sub. Class(); ? >
DESTRUCTOR void __destruct ( void ) Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent: : __destruct() in the destructor body. Like constructors, a child class may inherit the parent's destructor if it does not implement one itself. The destructor will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing.
DESTRUCTOR <? php class My. Destructable. Class { function __construct() { print "In constructorn"; $this->name = "My. Destructable. Class"; } function __destruct() { print "Destroying ". $this->name. "n"; } } $obj = new My. Destructable. Class(); ? >
- Slides: 40