More Related Content
Similar to Oop in php lecture 2 (20)
More from Mudasir Syed (20)
Oop in php lecture 2
- 1. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Hidaya Institute of
Science &
Technology
www.histpk.org
A Division of Hidaya Trust, Pakistan
- 2. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Object Oriented
Programming in
PHP
- 3. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Understanding Object-Oriented Programming
• Object-oriented programming is a style of coding that allows
developers to group similar tasks into classes.
• “don’t repeat yourself” (DRY) approach, and easy-to-maintain.
• Usually only one change is required to update the code.
• Maintaining code where data is declared over and over again.
- 4. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Understanding Objects and Classes
• Before you can get too deep into the finer points of OOP, a basic
understanding of the differences between objects and classes is
necessary.
- 5. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Recognizing the Differences Between Objects
and Classes
CLASS
•A class, for example, is like a
blueprint for a house.
•It defines the shape of the house on
paper, with relationships between the
different parts of the house clearly
defined and planned out.
•Even though the house doesn’t exist.
OBJECT
•An object, then, is like the actual
house built according to that
blueprint.
•The data stored in the object is like
the wood, wires, and concrete that
compose the house.
•when it all comes together, it
becomes an organized, useful house.
•More than one object can be built
from the same class.
- 6. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Structuring Classes
• The syntax to create a class is pretty straightforward
• Declare a class using the class keyword, followed by the name
of the class and a set of curly braces ({}):
• Syntax:
<?php
class MyClass
{
// Class properties and methods go here
}
?>
• After creating the class, a new class can be instantiated and
stored in a variable using the new keyword
$obj = new MyClass;
• To see the contents of the class, use var_dump():
• var_dump($obj);
• object(MyClass)#1 (0) { }
- 7. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Defining Class Properties
• To add data to a class, properties, or class-specific variables,
are used.
• These work exactly like regular variables, except they’re
bound to the object and therefore can only be accessed using
the object.
• The keyword public determines the visibility of the property,
which you’ll learn about a little later.
• To read this property and output it to the browser, reference
the object from which to read and the property to be read.
• echo $obj->prop1;
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
}
$obj = new MyClass;
var_dump($obj);
?>
- 8. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Defining Class Properties Cont…
• Because multiple instances of a class can exist, if the
individual object is not referenced, the script would be unable
to determine which object to read
• The use of the arrow (->) is an OOP construct that accesses
the contained properties and methods of a given object.
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
}
$obj = new MyClass;
echo $obj->prop1; // Output the property
?>
- 9. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Defining Class Methods
• Methods are class-specific functions.
• Individual actions that an object will be able to perform are
defined within the class as methods.
• For instance, to create methods that would set and get the
value of the class property $prop1, add the following to your
code. <?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1 . "<br />";
}
}
$obj = new MyClass;
echo $obj->prop1;
?>
- 10. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Defining Class Methods Cont…
• OOP allows objects to reference themselves using $this. When
working within a method.
• use $this in the same way you would use the object name
outside the class.
• To use these methods, call them just like regular functions,
but first, reference the object they belong to.
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1 . "<br />";
}
}
$obj = new MyClass;
echo $obj->getProperty(); // Get the property value
$obj->setProperty("I'm a new property value!"); // Set a new one
echo $obj->getProperty(); // Read it out again to show the change
?>
- 11. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Defining Class Methods Cont…
• The power of OOP becomes apparent when using multiple
instances of the same class.
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1 . "<br />";
}
}
$obj = new MyClass;
$obj2 = new MyClass;
// Get the value of $prop1 from both objects
echo $obj->getProperty();
echo $obj2->getProperty();
// Set new values for both objects
$obj->setProperty("I'm a new property value!");
$obj2->setProperty("I belong to the second instance!");
// Output both objects' $prop1 value
echo $obj->getProperty();
echo $obj2->getProperty();
?>
- 12. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Magic Methods in OOP
• PHP also provides a number of magic methods, or special
methods that are called when certain common actions occur
within objects.
Using Constructors and Destructors
• To handle this, PHP provides the magic method __construct(),
which is called automatically whenever a new object is
created.
• __CLASS__ returns the name of the class in which it is called;
this is what is known as a magic constant.
<?php
class MyClass
{
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
}
// Create a new object
$obj = new MyClass;
?>
- 13. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Magic Methods in OOP Cont…
Using Constructors and Destructors
•To call a function when the object is destroyed,
the __destruct() magic method is available.
•This is useful for class cleanup (closing a database connection,
for instance).
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}
}
// Create a new object
$obj = new MyClass;
// Output a message at the end of the file
echo "End of file.<br />";
?>
- 14. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Magic Methods in OOP Cont…
Using Constructors and Destructors
•When the end of a file is reached, PHP automatically releases all
resources.
•To explicitly trigger the destructor, you can destroy the object
using the function unset():
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}
}
// Create a new object
$obj = new MyClass;
unset($obj); // Destroy the object
// Output a message at the end of the file
echo "End of file.<br />";
?>
- 15. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Using Class Inheritance
• Classes can inherit the methods and properties of another
class using the extends keyword.
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1 . "<br />";
}
}
class MyOtherClass extends MyClass
{
public function newMethod()
{
echo "From a new method in " . __CLASS__ . ".<br />";
}
}
// Create a new object
$newobj = new MyOtherClass;
// Output the object as a string
echo $newobj->newMethod();
// Use a method from the parent class
echo $newobj->getProperty();
?>
- 16. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Overwriting Inherited Properties and Methods
• To change the behavior of an existing property or method in
the new class, you can simply overwrite it by declaring it
again in the new class:
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1 . "<br />";
}
}
class MyOtherClass extends MyClass
{
public function __construct()
{
echo "A new constructor in " . __CLASS__ . ".<br />";
}
public function newMethod()
{
echo "From a new method in " . __CLASS__ . ".<br />";
}
}
// Create a new object
$newobj = new MyOtherClass;
// Output the object as a string
echo $newobj->newMethod();
// Use a method from the parent class
echo $newobj->getProperty();
?>
- 17. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Preserving Original Method Functionality
While Overwriting Methods
• To add new functionality to an inherited method while keeping
the original method intact, use the parent keyword with
the scope resolution operator (::)
• This outputs the result of
both the parent
constructor and the new
class’s constructor.
class MyOtherClass extends MyClass
{
public function __construct()
{
parent::__construct(); // Call the parent class's constructor
echo "A new constructor in " . __CLASS__ . ".<br />";
}
public function newMethod()
{
echo "From a new method in " . __CLASS__ . ".<br />";
}
}
// Create a new object
$newobj = new MyOtherClass;
?>
- 18. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Preventing from Overriding
• If you declare any method as a final method, it can't be
overridden in any of its subclass.
• if you don't want someone to override your class methods,
declare it as final.
• If you execute the above code,
it will generate a fatal error
because class SubClass
tried to override a method in
SuperClass which was declared
as final.
<?
class SuperClass
{
public final function someMethod()
{
//..something here
}
}
class SubClass extends SuperClass
{
public function someMethod()
{
//..something here again, but it wont run
}
}
?>
- 19. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Preventing from Extending
• Similar to a final method, you can declare a class as final.
• It will prevent anyone from extending it.
• So if you declare any class, as shown in following example, it
is no more extensible.
• If you execute the code above, it will trigger the Fatal error.
<?
final class aclass
{
}
class bclass extends aclass
{
}
?>
- 20. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Assigning the Visibility of Properties and
Methods
• For added control over objects, methods and properties are
assigned visibility.
• This controls how and from where properties and methods
can be accessed.
• There are three visibility keywords.
• Public
• Protected
• Private
• In addition to its visibility, a method or property can be
declared as static, which allows them to be accessed without
an instantiation of the class.
• Visibility is a new feature as of PHP 5.
- 21. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Public Properties and Methods
• All the methods and properties you’ve used so far have been
public.
• This means that they can be accessed anywhere, both within
the class and externally.
- 22. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Protected Properties and Methods
• When a property or method is declared protected, it can only
be accessed within the class itself or in descendant
classes (classes that extend the class containing the
protected method).
• This means that they can be accessed anywhere, both within
the class and externally.
• Declare the getProperty() method as protected in MyClass and
try to access it directly from outside the class.
- 23. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Protected Properties and Methods Cont…
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}
public function setProperty($newval)
{
$this->prop1 = $newval;
}
protected function getProperty()
{
return $this->prop1 . "<br />";
}
}
class MyOtherClass extends MyClass
{
public function __construct()
{
parent::__construct();
echo "A new constructor in " . __CLASS__ . ".<br />";
}
public function newMethod()
{
echo "From a new method in " . __CLASS__ . ".<br />";
}
}
// Create a new object
$newobj = new MyOtherClass;
// Attempt to call a protected method
echo $newobj->getProperty();
?>
• Upon attempting to run this script, error will occur since
protected methods or properties can not be accessed
outside the class.
- 24. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Private Properties and Methods
• A property or method declared private is accessible only from
within the class that defines it.
• This means that even if a new class extends the class that
defines a private property, that property or method will not be
available at all within the child class.
• To demonstrate this, declare getProperty() as private
in MyClass, and attempt to call callProtected() from
MyOtherClass.
- 25. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Private Properties and Methods Cont…
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}
public function setProperty($newval)
{
$this->prop1 = $newval;
}
private function getProperty()
{
return $this->prop1 . "<br />";
}
}
class MyOtherClass extends MyClass
{
public function __construct()
{
parent::__construct();
echo "A new constructor in " . __CLASS__ . ".<br />";
}
public function callProtected()
{
return $this->getProperty();
}
}
// Create a new object
$newobj = new MyOtherClass;
// Use a method from the parent class
echo $newobj->callProtected();
?>
• Upon attempting to run this script, error will occur since
private methods or properties can not be accessed
outside the class and also in child class.
- 26. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Static Properties and Methods
• A method or property declared static can be accessed without
first instantiating the class.
• A static method and property can also be said as class
properties and methods.
• You simply supply the class name, scope resolution operator,
and the property or method name.
• To demonstrate this, add a static property called $count and a
static method called plusOne() to MyClass. Then set up
a do...while loop to output the incremented value of $count as
long as the value is less than 10.
- 27. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Static Properties and Methods Cont…
<?php
class MyClass
{
public static $count = 0;
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public static function plusOne()
{
return "The count is " . ++self::$count . ".<br />";
}
}
do
{
// Call plusOne without instantiating MyClass
echo MyClass::plusOne();
}
while ( MyClass::$count < 10 );
?>
class MyOtherClass extends MyClass
{
public function __construct()
{
parent::__construct();
echo "A new constructor in " . __CLASS__ . ".<br />";
}
public function callProtected()
{
return $this->getProperty();
}
}
• Note — When accessing static properties, the dollar sign
($) comes after the scope resolution operator.
- 28. © Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● www.hidayatrust.org / www,histpk.org
Static Properties and Methods Cont…
• When you load this script in your browser, the following
is output.
The count is 1.
The count is 2.
The count is 3.
The count is 4.
The count is 5.
The count is 6.
The count is 7.
The count is 8.
The count is 9.
The count is 10.