PHP/Class/Method Override — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 10:00, 26 мая 2010
Содержание
Calling an Overridden Method
<source lang="html4strict">
<html> <head> <title>Calling an Overridden Method</title> </head> <body> <?php class FirstClass{
var $name = "Joe"; function FirstClass( $n ) { $this->name = $n; } function sayHello() { print "my name is $this->name
"; }
} class second_class extends FirstClass {
function sayHello() { print "calling method from parent class -- "; FirstClass::sayHello(); }
} $test = new second_class("sub class"); $test->sayHello(); ?> </body> </html>
</source>
Class method override Demo
<source lang="html4strict">
<?php class myClass {
var $name = "A"; function myClass($n) { $this->name = $n; } function sayHello() { echo "HELLO! My name is ".$this->name; }
} class childClass extends myClass {
function sayHello() { echo "I will not tell you my name."; }
} $object1 = new childClass("a"); $object1 -> sayHello(); ?>
</source>
Method override for Rectangle class
<source lang="html4strict">
<?php
class Rectangle { public $height; public $width; public function __construct($width, $height) { $this->width = $width; $this->height = $height; } public function getArea() { return $this->height * $this->width; } } class Square extends Rectangle { public function __construct($size) { $this->height = $size; $this->width = $size; } public function getArea() { return pow($this->height, 2); } }
$obj = new Square(7); $a = $obj->getArea(); echo "$a"; ?>
</source>
The Method of a Child Class Overriding That of Its Parent
<source lang="html4strict">
<html> <head> <title>The Method of a Child Class Overriding That of Its Parent</title> </head> <body> <?php class FirstClass{
var $name = "first class"; function FirstClass( $n ){ $this->name = $n; } function sayHello(){ print "Hello my name is $this->name
"; }
} class second_class extends FirstClass {
function sayHello(){ print "say hi
"; }
} $test = new second_class("new name"); $test->sayHello(); ?> </body> </html>
</source>