CSC/ECE 517 Fall 2012/ch1 1w34 vd

From Expertiza_Wiki
Jump to navigation Jump to search

Re- implantation of methods in PHP 5

The object model in PHP5 was rewritten to include OO features such as final, abstract and visibility for classes and methods and improve the overall performance of the language. Re-implantation of methods in Php 5 can be achieved in the following manner:

Object Inheritance

This is an important OO feature that PHP uses in its object model. When a subclass extends from a parent class, it inherits all the public and protected methods from the parent class. The issues that affect how the inherited methods behave are:

Method Visibility

All methods that are defined as ‘public’ and ‘protected’ in the parent class are ‘visible’ in the subclass. Public and protected are access modifiers that define the visibility of methods between different classes. Methods defined as ‘private’ access are not visible in the subclass. Methods declared without any access keyword are ‘public’.
Example:

<?php

class GameClass
{


public function_construct(){ } //Declare a public constructor


public function GamePublic(){ } //Declare a public method
protected function GameProtected(){ } //Declare a protected method
private function GamePrivate(){ } //Declare a private method

function Play() //This is public
{ 
$this->GamePublic(); $this->GameProtected(); $this->GamePrivate();
 } } ?> $mygame = new GameClass;
$mygame->GamePublic(); // Works
$mygame->GameProtected(); // Fatal Error
$mygame->GamePrivate(); // Fatal Error
$mygame->Play(); // Public, Protected and Private work




class BoardGame extends GameClass
 {
//This is public

function PlayDice()
{

$this->GamePublic();

$this->GameProtected();

$this->GamePrivate(); // Fatal Error

 }

}

$myboard = new BoardGame;
$myboard->GamePublic(); // Works

$myboard->PlayDice(); // Public and Protected work, not Private


Overriding

If a subclass defines a new method with the same name and signature as that of the method from the parent class then an object of the subclass calling that method will execute the implementation of the method defined in the subclass. Example: change this example for overriding

<?php
class game
{
public function game-name($string)
 {
 echo 'Game: ' . $string . PHP_EOL;
 }
 
public function play()
 {
 echo 'I like this game.' . PHP_EOL;
 }
}
class chess-game extends game
{
 public function game-name($string)
 {
 echo 'Board Game: ' . $string . PHP_EOL;
 }
}
$gm = new game ();
$cg = new chess-game();
$game->game-name('cricket'); // Output: 'Game: cricket'
$gm->play();       // Output: 'I like this game' 
$cg->game-name('chess'); // Output: 'Board Game: chess'
$cg->play();       // Output: 'I like this game'
?>