PHP5 virtual function implementation method sharing

  • 2020-05-05 10:59:52
  • OfStack

See the following code:
 
<?php 
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(), so when B::y() is called, B::y() should call A::x() or B::x()? In C++, B::y() will call A::x() if A::x() is not defined as a virtual function, and B::y() will call B::x() if A:: y() is defined as a virtual function using the virtual keyword. However, in PHP5, the functionality of virtual functions is implemented by the self and $this keywords. If A::y() calls A::x() using self::x() in the parent class, A::y() calls A::x() whether or not A::x() is overridden. If the parent class A::y() USES $this-> x() calls A::x(), so if A::x() is overridden by B::x() in a subclass, A::y() will call B::x().

The above example runs as follows:
A::x() was called. A::y() was called. --
B::x() was called. A::z() was called.
virtual-function.php
 
<?php 
class ParentClass { 
static public function say( $str ) { 
static::do_print( $str ); 
} 
static public function do_print( $str ) { 
echo "<p>Parent says $str</p>"; 
} 
} 
class ChildClass extends ParentClass { 
static public function do_print( $str ) { 
echo "<p>Child says $str</p>"; 
} 
} 
class AnotherChildClass extends ParentClass { 
static public function do_print( $str ) { 
echo "<p>AnotherChild says $str</p>"; 
} 
} 
echo phpversion(); 
$a=new ChildClass(); 
$a->say( 'Hello' ); 
$b=new AnotherChildClass(); 
$b->say( 'Hello' ); 

Related articles: