Home > Backend Development > PHP Tutorial > Sharing the implementation method of virtual functions in PHP5_PHP tutorial

Sharing the implementation method of virtual functions in PHP5_PHP tutorial

WBOY
Release: 2016-07-21 15:31:02
Original
924 people have browsed it

Please look at the code below:

Copy code The code is as follows:

class A {
public function x() {
echo "A::x() was called.n";
}
public function y() {
self::x();
echo "A::y() was called.n";
}
public function z() {
$this->x();
echo "A::z() was called.n";
}
}
class B extends A {
public function x() {
echo "B::x() was called.n";
}
}
$b = new B();
$b->y();
echo "--n";
$b->z() ;
?>

In this example, A::y() calls A::x(), and B::x() overrides A::x() , then when calling B::y(), should B::y() call A::x() or B::x()? In C++, if A::x() is not defined as a virtual function, then B::y() (that is, A::y()) will call A::x(), and if A::x () is defined as a virtual function using the virtual keyword, then B::y() will call B::x(). However, in PHP5, the functionality of virtual functions is implemented by the self and $this keywords. If A::y() in the parent class calls A::x() using self::x(), then in the subclass no matter whether A::x() is overridden or not, A::y( ) calls A::x(); and if A::y() in the parent class calls A::x() using $this->x(), then if A::y() in the subclass ::x() is overridden by B::x(), A::y() will call B::x().

The results of the above example are as follows:
A::x() was called. A::y() was called. --
B::x() was called. A: :z() was called.
virtual-function.php
Copy code The code is as follows:

class ParentClass {
static public function say( $str ) {
static::do_print( $str );
}
static public function do_print( $ str ) {
echo "

Parent says $str

";
}
}
class ChildClass extends ParentClass {
static public function do_print( $str ) {
echo "

Child says $str

";
}
}
class AnotherChildClass extends ParentClass {
static public function do_print( $str ) {
echo "

AnotherChild says $str

";
}
}
echo phpversion();
$a=new ChildClass();
$a-> ;say( 'Hello' );
$b=new AnotherChildClass();
$b->say( 'Hello' );

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/323108.htmlTechArticlePlease see the code below: Copy the code The code is as follows: ?php class A { public function x() { echo " A::x() was called.n"; } public function y() { self::x(); echo "A::y() was called.n";...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template