Day 16: Working with class, variables and Inheritance

Variables are defined in class with ‘var’ keyword. By default variable declared with ‘var’ keyword is publicly assessed, you can also use public $variable instead of var $variable.

To access the variables declared in class, we have to use $this keyword. Like shown in blow example.

Program 45: Define and access variables in class

<?php
class myClass {
var $i = 9; //class variable
function display(){
$i = 7; //local variable
echo “value of i is “.$i; // it will display local variable (i.e. 7)
echo “<br/>value of class i is “.$this->i; // it will display class variable (i.e. 9)
}
}
$obj = new myClass();
$obj->display();
?>

Public variable of the class can be display outside the class with object of that class, like in blow example, $b is a public variable displayed outside the class and $a is a private variable can’t be display outside the class.

Program 46: Access variables outside the class

<?php
class myClass {
private $a = 9;
var $b = 9;
}
$obj = new myClass();
echo “Variable outside the class “.$obj->b;
?>

Inheritance in PHP

Inheritance introduced in php5 version. Inheritance is one of the feature of object oriented programming. Through inheritance we can get all property and method of one class in another class. Class who inherit feature of another class known as child class and class which is being inherited is known as parent class. ‘extends’ is the keyword that enables inheritance in PHP.

Program 47: Inheritance – Example 1:

<?php
class A {
public function Hello($name) {
echo ‘<br/>Hello ‘ . $name;
}
public function Bay() {
echo ‘<br/>Bay every body!’;
}
}

class B extends A {
public function display() {
echo ‘<br/>i am in chid’;
}
}

$objA = new A();
$objB = new B();
$objA->Hello(‘Albert’);
$objA->Bay();
$objB->Hello(‘Jhon Methue’); //Parent class’s method called with child object
$objB->Bay(); //Parent class’s method called with child object
?>

Program 48: Inheritance – Example 2:

<?php
class A {
protected $a = 3;
function displayA() {
echo “<br/>I am in a”;
echo “<br/>Value of a is “.$this->a;
}
}
class B extends A {
function displayB() {
echo “<br/>I am in b”;
echo “<br/>Value of a from b is “.$this->a;
}
}

class C extends B {
function displayC() {
echo “<br/>I am in c”;
}
}
$objC = new C();
$objC->displayA();
$objC->displayB();
$objC->displayC();
?>


Output:
I am in a
Value of a is 3
I am in b
Value of a from b is 3
I am in c

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.