PHP With Oops Concept
PHP With Oops Concept
PHP With Oops Concept
CONCEPT
• In PHP, declare a class using the class keyword, followed by the name
of the class and a set of curly braces ({}).
<?php
class MyClass
{
// Class properties and methods go here
}
?>
In PHP, to see the contents of the class, use var_dump(). The var_dump() function is used to display
the structured information (type and value) about one or more variables.
Syntax:
var_dump($obj);
Object:
A class defines an individual instance of the data structure. We define a class once and then make many objects that
belong to it. Objects are also known as an instance.
An object is something that can perform a set of related activities.
Syntax:
<?php
class MyClass
{
// Class properties and methods go here
}
$obj = new MyClass;
var_dump($obj);
?>
• Do not quote the class name, or you’ll get a compilation error:
• Some classes permit you to pass arguments to the new call. The class’s documentation
should say whether it accepts arguments. If it does, you’ll create objects like this:
• The class name does not have to be hardcoded into your program. You can supply the
class name through a variable:
$class = "Person";
$object = new $class;
// is equivalent to
$object = new Person;
• Specifying a class that doesn’t exist causes a runtime error.
• For example:
$clan = $rasmus->family("extended");
• Example
<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit);
?>
The $this Keyword
• The $this keyword refers to the current object, and is only available
inside methods.
• Look at the following example:
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
?>
• So, where can we change the value of the $name property? There are two ways:
1. Inside the class (by adding a set_name() method and use $this):
<?php
class Fruit {
public $name;
function set_name($name) {
$this->name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");
echo $apple->name;
?>
2. Outside the class (by directly changing the property value):
<?php
class Fruit {
public $name;
}
$apple = new Fruit();
$apple->name = "Apple";
echo $apple->name;
?>
• Here’s a simple class definition of the Person class that shows the $this variable in action:
class Person
{
public $name = '';
function getName()
{
return $this->name;
}
function setName($newName)
{
$this->name = $newName;
}
}
Static methods and properties
• When declaring a class, you define which properties and methods are
static using the static access property.
• A static method is one that is called on a class, not on an object. Such
methods cannot access properties. The name of a static method is the
class name followed by two colons and the function name.
• For instance, this calls the p() static method in the HTML class:
HTML::p("Hello, world");
• To declare a method as a static method, use the static keyword. Inside of static methods the variable
$this is not defined. For example:
class HTMLStuff
{
static function startTable()
{
echo "<table border=\"1\">\n";
}
static function endTable()
{
echo "</table>\n";
}
}
HTMLStuff::startTable();
// print HTML table rows and columns
HTMLStuff::endTable();
• A class can have both static and non-static methods. A static method can be accessed
from a method in the same class using the self keyword and double colon (::):
• Example
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
public function __construct() {
self::welcome();
}
}
new greeting();
?>
• Static methods can also be called from methods in other classes. To do this, the static method should be
public :
• Example
<?php
class greeting {
public static function welcome() {
echo "Hello World!";
}
}
class SomeOtherClass {
public function message() {
greeting::welcome();
}
}
$obj = new SomeOtherClass();
$obj->message();
?>
Static Properties
• Static properties can be called directly - without creating an instance
of a class.
• Static properties are declared with the static keyword
• Syntax
<?php
class ClassName {
public static $staticProp = “PHP";
}
?>
• To access a static property use the class name, double colon (::), and
the property name:
• Syntax
ClassName::$staticProp;
Example
<?php
class pi {
public static $value = 3.14159;
}
$pi = new pi();
echo $pi->staticValue();
?>
Access modifiers
• Properties and methods can have access modifiers which control
where they can be accessed.
• There are three access modifiers:
1. Public : the property or method can be accessed from everywhere.
This is default
2. Protected : the property or method can be accessed within the class
and by classes derived from that class
3. Private : the property or method can ONLY be accessed within the
class
Example
<?php
class Fruit {
public $name;
protected $color;
private $weight;
}
$mango = new Fruit();
$mango->name = 'Mango'; // OK
$mango->color = 'Yellow'; // ERROR
$mango->weight = '300'; // ERROR
?>
Example
<?php
class Fruit {
public $name;
public $color;
public $weight;
$mango = new Fruit();
$mango->set_name('Mango'); // OK
$mango->set_color('Yellow'); // ERROR
$mango->set_weight('300'); // ERROR
?>
class Person
{
public $age;
public function __construct()
{
$this->age = 0;
}
public function incrementAge()
{
$this->age += 1;
$this->ageChanged();
}
protected function decrementAge()
{
$this->age −= 1;
$this->ageChanged();
}
private function ageChanged()
{
echo "Age changed to {$this->age}";
}
}
class SupernaturalPerson extends Person
{
public function incrementAge()
{
// ages in reverse
$this->decrementAge();
}
}
$person = new Person;
$person->incrementAge();
$person->decrementAge(); // not allowed
$person->ageChanged(); // also not allowed
$person = new SupernaturalPerson;
$person->incrementAge(); // calls decrementAge under the hood
Declaring Properties
• In the previous definition of the Person class, we explicitly declared the $name property.
• Property declarations are optional and are simply a courtesy to whomever maintains your program.
• It’s good PHP style to declare your properties, but you can add new properties at any time.
• Here’s a version of the Person class that has an undeclared $name property:
class Person
{
function getName()
{
return $this->name;
}
function setName($newName)
{
$this->name = $newName;
}
}
• You can assign default values to properties, but those default values
must be simple constants:
• public $name = "J Doe"; // works
• public $age = 0; // works
• public $day = 60 * 60 * 24; // doesn't work
Declaring Constants
• Like global constants, assigned through the define() function, PHP provides a way to assign
constants within a class.
• Like static properties, constants can be accessed directly through the class or within object methods
using the self notation.
• Once a constant is defined, its value cannot be changed:
class PaymentMethod
{
const TYPE_CREDITCARD = 0;
const TYPE_CASH = 1;
}
echo PaymentMethod::TYPE_CREDITCARD;
• As with global constants, it is common practice to define class constants with uppercase identifiers.
CONSTRUCTOR
• PHP 5 allows developers to declare constructor methods for classes.
• Constructor is suitable for any initialization that the object may need
before it is used.
• We can design constructor using "__construct" or same name as
class name.
• Parent constructors are not called implicitly if the child class defines a
constructor. In order to run a parent constructor, a call
to parent::__construct().
• Notice that the construct function starts with two underscores (__)!
Example
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit("Apple");
echo $apple->get_name();
?>
<?php
class Fruit {
public $name;
public $color;
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function get_name() {
return $this->name;
}
function get_color() {
return $this->color;
}
}
$apple = new Fruit("Apple", "red");
echo $apple->get_name();
echo "<br>";
echo $apple->get_color();
?>
DESTRUCTOR
• PHP 5 introduces a destructor concept similar to that of other object-
oriented languages, such as C++.
• The destructor method will be called as soon as all references to a
particular object are removed or when the object is explicitly
destroyed in any order in shutdown sequence.
• We create destructor by using "__destruct" function.
• Notice that the destruct function starts with two underscores (__)!
The example below has a __construct() function that is automatically called when you create
an object from a class, and a __destruct() function that is automatically called at the end of
the script:
<?php
class Fruit {
public $name;
public $color;
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}
$apple = new Fruit("Apple");
?>
<?php
class Fruit {
public $name;
public $color;
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function __destruct() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
$apple = new Fruit("Apple", "red");
?>
Declaring Constants
• Like global constants, assigned through the define() function, PHP provides a way to assign constants
within a class.
• Like static properties, constants can be accessed directly through the class or within object methods
using the self notation.
• Class constants are different than normal variables, as we do not need $ to declare the class
constants.
• Once a constant is defined, its value cannot be changed:
class PaymentMethod
{
const TYPE_CREDITCARD = 0;
const TYPE_CASH = 1;
}
echo PaymentMethod::TYPE_CREDITCARD;
<?php
//create class
class hello
{
//create constant variable
const a= "This is const keyword example";
}
//call constant variable.
echo hello::a;
?>
Inheritance
• It is a concept of accessing the features of one class from another class.
If we inherit the class features into another class, we can access both
class properties. We can extends the features of a class by using
'extends' keyword.
• It supports the concept of hierarchical classification.
• Inheritance has three types, single, multiple and multilevel
Inheritance.
• PHP supports only single inheritance, where only one class can
be derived from single parent class.
• We can simulate multiple inheritance by using interfaces.
class Person
{
public $name, $address, $age;
}
class Employee extends Person
{
public $position, $salary;
}
<?php
class a
{
function fun1()
{
echo “Welcome";
}
}
class b extends a
{
function fun2()
{
echo “to PHP class";
}
}
$obj= new b();
$obj->fun1();
?>
<?php
class demo
{
public function display()
{
echo "example of inheritance ";
}
}
class demo1 extends demo
{
public function view()
{
echo "in php";
}
}
$obj= new demo1();
$obj->display();
$obj->view();
?>
ABSTRACT CLASS
• An abstract class is a mix between an interface and a class. It can be
define functionality as well as interface.
• Classes extending an abstract class must implement all of the abstract
methods defined in the abstract class.
• An abstract class is declared the same way as classes with the
addition of the 'abstract' keyword. abstract class MyAbstract
{
//Methods
}
//And is attached to a class using the extends keyword.
class Myclass extends MyAbstract
{
//class methods
}
<?php
abstract class a
{
abstract public function dis1();
abstract public function dis2();
}
class b extends a
{
public function dis1()
{
echo "javatpoint";
}
public function dis2()
{
echo "SSSIT";
}
}
$obj = new b();
$obj->dis1();
$obj->dis2();
?>
<?php
abstract class Animal
{
public $name;
public $age;
public function Describe()
{
return $this->name . ", " . $this->age . " years old";
}
abstract public function Greet();
}
class Dog extends Animal
{
public function Greet()
{
return "Woof!";
}
public function Describe()
{
return parent::Describe() . ", and I'm a dog!";
}
}
$animal = new Dog();
$animal->name = "Bob";
$animal->age = 7;
echo $animal->Describe();
echo $animal->Greet();
?>
Interface
• An interface is similar to a class except that it cannot contain code.
• An interface can define method names and arguments, but not the
contents of the methods.
• Any classes implementing an interface must implement all methods
defined by the interface.
• A class can implement multiple interfaces.
• An interface is declared using the "interface" keyword.
• Interfaces can't maintain Non-abstract methods.
Here’s the syntax for an interface definition:
interface interfacename
{
[ function functionname();
...
]
}
• To declare that a class implements an interface, include the implements keyword and
any number of interfaces, separated by commas:
interface Printable
{
function printOutput();
}
class ImageComponent implements Printable
{
function printOutput()
{
echo "Printing an image...";
}
}
• An interface may inherit from other interfaces (including multiple interfaces) as long
as none of the interfaces it inherits from declare methods with the same name as those
declared in the child interface.
<?php
interface i1
{
public function fun1();
}
interface i2
{
public function fun2();
}
class cls1 implements i1,i2
{
function fun1()
{
echo “welcome";
}
function fun2()
{
echo “PHP";
}
}
$obj= new cls1();
$obj->fun1();
$obj->fun2();
?>
Difference between Abstract class and
Interfaces.
Abstract class: Interface:
Abstract class comes under partial abstraction. Interface comes under fully abstraction.
Abstract classes can maintain abstract methods and Interfaces can maintain only abstract methods.
non abstract methods.
In abstract classes, we can create the variables. In interfaces, we can't create the variables.
In abstract classes, we can use any access specifier. In interface, we can use only public access specifier.
By using 'extends' keyword we can access the abstract By using 'implement' keyword we can get interface
class features from derived class. from derived class.