PHP What is OOP? OOP stands for Object-Oriented ..., Summaries of Physics

You define a class once and then make many objects that belong to it. Objects are also known as instance. • Member Variable − These are the variables defined ...

Typology: Summaries

2021/2022

Uploaded on 09/27/2022

mrbean3
mrbean3 🇬🇧

4

(5)

214 documents

1 / 46

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
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
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e

Partial preview of the text

Download PHP What is OOP? OOP stands for Object-Oriented ... and more Summaries Physics in PDF only on Docsity!

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.

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**

$apple->name = "Apple"; ?> PHP - instanceof You can use the instanceof keyword to check if an object belongs to a specific class: Example

**Object Oriented Programming in PHP** We can imagine our universe made of different objects like sun, earth, moon etc. Similarly we can imagine our car made of different objects like wheel, steering, gear etc. Same way there is object oriented programming concepts which assume everything as an object and implement a software using different objects. **Object Oriented Concepts** Before we go in detail, lets define important terms related to Object Oriented Programming.  **Class** − This is a programmer-defined data type, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object.  **Object** − An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance.  **Member Variable** − These are the variables defined inside a class. This data will be invisible to the outside of the class and can be accessed via member functions. These variables are called attribute of the object once an object is created.

Member function − These are the function defined inside a class and are used to access object data.  Inheritance − When a class is defined by inheriting existing function of a parent class then it is called inheritance. Here child class will inherit all or few member functions and variables of a parent class.  Parent class − A class that is inherited from by another class. This is also called a base class or super class.  Child Class − A class that inherits from another class. This is also called a subclass or derived class.  Polymorphism − This is an object oriented concept where same function can be used for different purposes. For example function name will remain same but it take different number of arguments and can do different task.  Overloading − a type of polymorphism in which some or all of operators have different implementations depending on the types of their arguments. Similarly functions can also be overloaded with different implementation.  Data Abstraction − Any representation of data in which the implementation details are hidden (abstracted).  Encapsulation − refers to a concept where we encapsulate all the data and member functions together to form an object.  Constructor − refers to a special type of function which will be called automatically whenever there is an object formation from a class.  Destructor − refers to a special type of function which will be called automatically whenever an object is deleted or goes out of scope. Defining PHP Classes The general form for defining a new class in PHP is as follows −

The variable $this is a special variable and it refers to the same object ie. itself. Creating Objects in PHP Once you defined your class, then you can create as many objects as you like of that class type. Following is an example of how to create object using new operator. $physics = new Books; $maths = new Books; $chemistry = new Books; Here we have created three objects and these objects are independent of each other and they will have their existence separately. Next we will see how to access member function and process member variables. Calling Member Functions After creating your objects, you will be able to call member functions related to that object. One member function will be able to process member variable of related object only. Following example shows how to set title and prices for the three books by calling member functions. $physics->setTitle( "Physics for High School" ); $chemistry->setTitle( "Advanced Chemistry" ); $maths->setTitle( "Algebra" ); $physics->setPrice( 10 ); $chemistry->setPrice( 15 ); $maths->setPrice( 7 ); Now you call another member functions to get the values set by in above example − $physics->getTitle(); $chemistry->getTitle(); $maths->getTitle(); $physics->getPrice(); $chemistry->getPrice(); $maths->getPrice(); This will produce the following result − Physics for High School Advanced Chemistry

Algebra 10 15 7 Constructor Functions Constructor Functions are special type of functions which are called automatically whenever an object is created. So we take full advantage of this behaviour, by initializing many things through constructor functions. PHP provides a special function called __construct() to define a constructor. You can pass as many as arguments you like into the constructor function. Following example will create one constructor for Books class and it will initialize price and title for the book at the time of object creation. function __construct( $par1, $par2 ) { $this->title = $par1; $this->price = $par2; } Now we don't need to call set function separately to set price and title. We can initialize these two member variables at the time of object creation only. Check following example below − $physics = new Books( "Physics for High School", 10 ); $maths = new Books ( "Advanced Chemistry", 15 ); $chemistry = new Books ("Algebra", 7 ); /* Get those set values */ $physics->getTitle(); $chemistry->getTitle(); $maths->getTitle(); $physics->getPrice(); $chemistry->getPrice(); $maths->getPrice(); This will produce the following result − Physics for High School Advanced Chemistry Algebra

Now apart from inherited functions, class Novel keeps two additional member functions. Function Overriding Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class. In the following example getPrice and getTitle functions are overridden to return some values. function getPrice() { echo $this->price. "
"; return $this->price; } function getTitle(){ echo $this->title. "
"; return $this->title; } Public Members Unless you specify otherwise, properties and methods of a class are public. That is to say, they may be accessed in three possible situations −  From outside the class in which it is declared  From within the class in which it is declared  From within another class that implements the class in which it is declared Till now we have seen all members as public members. If you wish to limit the accessibility of the members of a class then you define class members as private or protected. Private members By designating a member private, you limit its accessibility to the class in which it is declared. The private member cannot be referred to from classes that inherit the class in which it is declared and cannot be accessed from outside the class. A class member can be made private by using private keyword infront of the member.

class MyClass { private $car = "skoda"; $driver = "SRK"; function __construct($par) { // Statements here run every time // an instance of the class // is created. } function myPublicFunction() { return("I'm visible!"); } private function myPrivateFunction() { return("I'm not visible outside!"); } } When MyClass class is inherited by another class using extends, myPublicFunction() will be visible, as will $driver. The extending class will not have any awareness of or access to myPrivateFunction and $car, because they are declared private. Protected members A protected property or method is accessible in the class in which it is declared, as well as in classes that extend that class. Protected members are not available outside of those two kinds of classes. A class member can be made protected by using protected keyword in front of the member. Here is different version of MyClass − class MyClass { protected $car = "skoda"; $driver = "SRK"; function __construct($par) { // Statements here run every time // an instance of the class // is created. } function myPublicFunction() {

In this class, requiredMargin is a constant. It is declared with the keyword const, and under no circumstances can it be changed to anything other than 1.7. Note that the constant's name does not have a leading $, as variable names do. Abstract Classes An abstract class is one that cannot be instantiated, only inherited. You declare an abstract class with the keyword abstract , like this − When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child; additionally, these methods must be defined with the same visibility. abstract class MyAbstractClass { abstract function myAbstractFunction() { } } Note that function definitions inside an abstract class must also be preceded by the keyword abstract. It is not legal to have abstract function definitions inside a non-abstract class. Static Keyword Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can). Try out following example −

staticValue(). "\n"; ?> **Final Keyword**

PHP 5 introduces the final keyword, which prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended. Following example results in Fatal error: Cannot override final method BaseClass::moreTesting()

"; } final public function moreTesting() { echo "BaseClass::moreTesting() called
"; } } class ChildClass extends BaseClass { public function moreTesting() { echo "ChildClass::moreTesting() called
"; } } ?> **Calling parent constructors** Instead of writing an entirely new constructor for the subclass, let's write it by calling the parent's constructor explicitly and then doing whatever is necessary in addition for instantiation of the subclass. Here's a simple example − 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); }

Definition and Usage The extends keyword is used to derive a class from another class. This is called inheritance. A derived class has all of the public and protected properties of the class that it is derived from. 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

$mango->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 ?>