OOP In PHP (Object Oriented Programming in PHP)

Posted by chaabant on Mar 28, 2008

This is a basic introduction on how to use OOP – Oriented Programming In php

Declaring a Class

class myClass {
// Class contents go here
}[/code]

Instantiating an Object

1
$myClassInst = new myClass();
$myClassInst = new myClass();

OOP Class Inheritance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class a {
 
function test()
{
echo "a::test called";
}
 
function func()
{
echo "a::func called";
}
}
 
 
class b extends a {
 
function test()
{
echo "b::test called";
}
}
 
class c extends b {
 
function test()
{
parent::test();
}
 
}
 
class d extends c {
 
function test()
{
b::test();
}
 
}
 
$a = new a();
$b = new b();
$c = new c();
$d = new d();
 
$a->test(); // Outputs "a::test called"
$b->test(); // Outputs "b::test called"
$b->func(); // Outputs "a::func called"
$c->test(); // Outputs "b::test called"
$d->test(); // Outputs "b::test called"
class a {

function test()
{
echo "a::test called";
}

function func()
{
echo "a::func called";
}
}

class b extends a {

function test()
{
echo "b::test called";
}
}

class c extends b {

function test()
{
parent::test();
}

}

class d extends c {

function test()
{
b::test();
}

}

$a = new a();
$b = new b();
$c = new c();
$d = new d();

$a->test(); // Outputs "a::test called"
$b->test(); // Outputs "b::test called"
$b->func(); // Outputs "a::func called"
$c->test(); // Outputs "b::test called"
$d->test(); // Outputs "b::test called"