PHP/Class/Method Override — различия между версиями

Материал из Web эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 07:00, 26 мая 2010

Calling an Overridden Method

<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<br>";
    }
}
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>



Class method override Demo

<?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();
?>



Method override for Rectangle class

<?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";
?>



The Method of a Child Class Overriding That of Its Parent

<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<br>";
    }
}
class second_class extends FirstClass {
     function sayHello(){
        print "say hi<br>";
     }
}
$test = new second_class("new name");
$test->sayHello();
?>
</body>
</html>