interface Intf
{
public function f();
}
interface Intg
{
public function g();}
//public function f(); // error in case of multiple implementing (with Intf)
//simple implementation
class Cf implements Intf
{
public function f(){ print "interface Cf, function f"; }}
//multiple implementation
class Cfg implements Intf, Intg
{
public function f(){ print "interface Cfg, function f"; }}
public function g(){ print "interface Cfg, function g"; }
//tipe hinting with interface name
function callF(Intf $obj)// tpye hinting not compulsory
{
$obj->f();}
//$obj->g(); // runtime error
//pass a class that implements the interface "Intf"
callF(new Cf()); // OUTPUT: interface Cf, function f
//callF("hello");// error, argum. must implement interface Intf
//instanceof sample
function callAll($obj)// type hinting "Intf" or "Intg" don't generate warnings
{
if ($obj instanceof Intf) $obj->f(); // (1) //interface Cfg, function f}
if ($obj instanceof Intg) $obj->g(); // (2) //interface Cfg, function g
//a "Cfg" object is an instance of both interfaces
callAll(new Cfg());
No comments:
Post a Comment