• No results found

OOP – Object Oriented Programming

In document Athena Giao Trinh Php Mysql (Page 95-109)

Object-Oriented Programming

Keywords: object, class, instance, inheritance, encapsulation, access,

constructor, destructor, property, method, visibility, parent, self, this,

override, public, protected, private.

Subjects:

8.1.

OOP Fundamentals

8.2.

Properties

8.3.

Methods

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

96

8.1.

OOP Fundamentals:

8.1.1. What is OOP ?

- As we mentioned previously, the basic element of OOP is the class. A class contains the

definition of data elements (or properties) and functions (or methods) that share some

common trait and can be encapsulated in a single structure.

8.1.2. Declaring Class: Class name is case-insensitive

class ClassName {

// Some Properties // Some Methods }

8.1.3. Instantiating an Object: To create an instance of a class, a new object must be

created and assigned to a variable. An object will always be assigned when creating a new

object unless the object has a constructor defined that throws an exception on error.

Classes should be defined before instantiation.

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

97

Ex:

$myClassInstance = new MyClass(); $copyInstance = $myClassInstance;

8.2.

Properties:

8.2.1. Declaration & Visibility: The default value must be a constant expression, not

(for example) a variable, a class member or a function call.

Ex:

class foo { //valid declaration public $name; protected $age; private $type;

public $var1 = "Test"; // String public $var2 = 1.23; // Numeric value public $var3 = array(1, 2, 3); // Array //invalid declaration

$var4 = TRUE;

public $var1 = 'hello '.'world'; public $var2 = <<<EOD

hello world EOD;

public $var3 = 1+2;

public $var4 = self::myStaticMethod(); public $var5 = $myVar;

}

8.2.2. Constant:

Ex:

class foo {

const BAR = 'Hello World'; }

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

98

8.3.

Methods:

8.3.1. Declaration:

- A class method/functions is the behavior/functionality of a class i.e. they provide the

necessary code for the class in which it is defined.

- A class method is exactly similar to PHP functions, it’s just that class functions are declared

inside classes and accessed using the -> (arrow operator / dereferencing operator).

- Methods can also be declared as either public, protected or private.

- Example:

class MyClass {

public function myFunction() {

echo 'You called MyClass::myFunction'; //call the private function

$this->myPrivate(); }

private function myPrivate() {

echo "\nThis is a private function."; }

}

$obj = new MyClass(); $obj->myFunction(); //Displays:

You called MyClass::myFunction This is a private function.

- A pseudo-variable, $this is available when a method is called from within an object context.

Ex:

class Shirt {

public $color;

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

99

{

echo $this->color; }

public function say() {

$this->getColor(); }

}

$redShirt = new Shirt(); $redShirt->color = 'Red'; $blueShirt = new Shirt(); $blueShirt->color = 'Blue';

$redShirt->say(); // Displays 'Red' $blueShirt->say(); // Displays 'Blue'

8.3.2. Constructor: Using

__construct()

method.

- A constructor is a special function of a class that is automatically executed whenever an

object of a class gets instantiated.

- It is needed as it provides an opportunity for doing necessary setup operations like

initializing class variables, opening database connections or socket connections, etc. In

simple terms, it is needed to setup the object before it can be used.

- In PHP5 a constructor is defined by implementing the __construct() method. This naming

style has been introduced in PHP5. In PHP4, the name of the constructor was the same

name as that of the class. So, for example if you had a class Customer, you would have to

implement a function Customer().

- PHP5 to be backward complaint also supports the PHP4 rule. When an object is created,

PHP5 searches for __construct() first. If __construct() is not defined it then searches for a

method with the same that of the class. However, if you define both; PHP5 will first search

for __construct() method and execute it if available, otherwise it will execute the same

class name function.

- Unlike other programming languages where overloaded argument constructors is possible, in

PHP5 you cannot overload constructors.

- Example:

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

100

{ public $color; function __construct($myColor) { $this->color = $myColor; }

private function getColor() {

echo $this->color; }

public function say() {

$this->getColor(); }

}

$redShirt = new Shirt('Red'); $blueShirt = new Shirt('Blue'); $redShirt->say(); // Displays 'Red' $blueShirt->say(); // Displays 'Blue'

8.3.3. Destructor: Using

__destruct()

method.

-

A destructor is a special function of a class that is automatically executed whenever an object of a class is destroyed:

1.

it goes out of scope,

2.

when you specifically set it to null,

3.

when you unset it or when the program execution is over.

- A PHP5 destructor is defined by implementing the __destruct() method. In PHP4 however, the concept of a destructor did not exist.

- A destructor cannot take any arguments. - Example:

class Shirt {

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

101

function __construct($myColor) { $this->color = $myColor; } function __destruct() {

echo $this->color . ' is dead'; }

private function getColor() {

echo $this->color; }

public function say() {

$this->getColor(); }

}

$redShirt = new Shirt('Red'); $blueShirt = new Shirt('Blue'); $redShirt->say(); // Displays 'Red' $blueShirt->say(); // Displays 'Blue'

$redShirt = null; // Displays 'Red is dead'; unset($blueShirt); // Displays 'Blue is dead';

8.3.4. Static Property & Method:

- Declaring class properties or methods as static makes them accessible without needing an

instantiation of the class. A property declared as static can not be accessed with an

instantiated class object (though a static method can).

- Because static methods are callable without an instance of the object created, the pseudo

variable $this is not available inside the method declared as static.

- Static properties cannot be accessed through the object using the arrow operator ->.

- Example:

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

102

{

static $var1 = 'hello';

public static function myFunction() {

echo 'Hello World'; }

}

$obj = new MyClass();

$obj->myFunction(); // Displays "Hello World" echo $obj->var1; // Invalid, it shows a notice MyClass::myFunction(); // Displays "Hello World" echo MyClass::$var1; // Displays "hello"

8.4.

Inheritance & Overriding:

8.4.1. Inheritance:

- Inheritance is the mechanism of deriving a new class from an existing class. It allows a sub-

class / child class to share/inherit the properties and methods of a base-class or parent

class.

- To inherit in PHP5, you should use the keyword ‘extends’ in the class definition. In PHP5

only single inheritance is allowed. Ex:

class Person {

private $name; private $address;

public function getName() {

return $this->name; }

}

class Customer extends Person {

private $customer_id; private $record_date;

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

103

public getCustomerId() {

return $this->customer_id; }

public getCustomerName() {

return $this->getName();// getName() is in Person }

}

8.4.2. Access specifiers in Inheritance:

+ Public: A public access specifier allows the properties and methods to be accessed from

anywhere in the script. Please note that if you declare any properties or method without a

access specifier it is considered as ‘public’. Ex:

Class Person {

public $age = 20; }

Class Customer extends Person {

}

$myCustomer = new Customer(); echo $myCustomer->age;

+ Private: A private access specifier is used to hide properties and methods. A method or

property declared as private can only be accessed by the class itself and neither the outside

program nor the derived class can have access to it. The reason why properties are

declared private is to avoid the outside programs to either accidently modify the values

without necessary validation. Ex:

class Customer {

private $name; public $age;

public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } $c = new Customer("Sunil","28");

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

104

+ Protected: A protected access specifier allows the derived class to access the properties and

methods of the base class. Ex:

class Person {

protected $name; }

class Customer extends Person {

function setName($name) {

//this works as $name is protected in Person

$this->name = $name; } } $c1 = new Customer(); $c1->setName("Sunil");

$c1->name = "Sunil"; // Displays an error as $name is protected and not

public

8.4.3. Overriding:

- Method overriding is when the method of base class is re-defined with the same name,

function signature and access specifier (either public or protected) of the derived class. The

reason to override method is to provide additional functionality over and above what has

been defined in the base class. Ex:

class Bird {

public function fly() {

echo "Fly method of Bird Class called"; }

}

class Eagle extends Bird {

public function fly() {

echo "Fly method of the Eagle Class called"; }

}

class Chicken extends Bird {

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

105

public function fly() {

echo "Fly method of the Chicken Class called"; } } $e = new Eagle(); $c = new Chicken();

$e->fly(); // Displays "Fly method of the Eagle Class called" echo "\n";

$c->fly(); // Displays "Fly method of the Chicken Class called"

- Examples:

class Car { protected $color; protected $hoursepower; protected $seatCount; protected $type;

public $size = 'Small'; function __construct() {

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

106

$this->type = 'Car'; }

public function run() {

echo $this->type . ' is running !'; }

}

class RaceCar extends Car {

private $nitro;

function __construct() {

$this->type = 'Race Car'; $this->size = 'Medium'; }

public function run() {

Echo $this->type . ' is racing !'; }

}

class Truck extends Car {

private $trailer;

protected $type = 'Truck'; }

$car = new Car();

$car->run(); // Displays "Car is running!" $racecar = new RaceCar();

$racecar->run(); // Displays "Race Car is racing!" $truck = new Truck();

$truck->run(); // Display ?

8.4.4. Invoke Parent Methods:

- When you override a method of the base class, it’s functionality is completely hidden unless

it has been explicitly invoked from the child class. To invoke a parent class method you

should use the keyword parent followed by the scope resolution operator followed by the

name of the method as mentioned below.

- Syntax:

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

107

- Example:

class Person {

public function showData() {

echo "This is Person's showData()\n"; }

}

class Customer extends Person {

public function showData() {

parent::showData();

echo "This is Customer's showData()\n"; } } $c = new Customer(); $c->showData(); // Displays

This is Person’s showData() This is Customer’s showData()

8.4.5. Invoke Parent Constructor & Destructor:

- We can get the parent PHP5 constructor and PHP5 Destructor to be invoked in the same way

as invoking the parent method

- Example:

class Person {

public function __construct() {

echo "This is Person's __construct()\n"; }

public function __destruct() {

echo "This is Person's __destruct()\n"; }

}

class Customer extends Person {

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

108

{

parent::__construct();

echo "This is Customer's __construct()\n"; }

public function __destruct() {

parent::__destruct();

echo "This is Customer's __destruct()\n"; }

}

$c = new Customer(); // Displays

This is Person’s __construct() This is Customer’s __construct() This is Person’s __destruct() This is Customer’s __destruct()

Chapter Exercise:

Website: Design a webpage to display form for user login. The username is an email, and the password must be at least 6 characters. Password must be alphanumerical characters (a-z, A-Z, 0-9). If login success, displays the name of the user (extract from email) and the number of page which is refreshed by user.

Ex: enter email: [email protected], password: abc3456ad5, website will display: Hello rasmus !

You refreshed 3 times.

A> Write photo album function for the user (after login)

a. Upload images (png,gif,jpeg) – 5 images in a submit form

b. Store images in directory "uploads/images/".

c. Max file size: 300KB

d. File name: USERNAME_imagename

e. If image existed, append the letter "i" after name part. Ex: rasmus_image1.gif exists, will be renamed to rasmus_image1i.gif

B>

Find all classes in application. Ex: User…

THÀNH VIÊN HIP HI AN TOÀN THÔNG TIN VIT NAM- VNISA WWW.ATHENA.EDU.VN . TEL: 1900 54 54 56 -090 7879 477

VO DUY TUAN PHP Beginner & Intermediate

ATHENA INFORMATION TRAINING

109

In document Athena Giao Trinh Php Mysql (Page 95-109)

Related documents