Interfaces in PHP can only play a role in defining constraint classes. Although not as intuitive as C#/Java, based on the encapsulation requirements of OOP, using interfaces can improve the scalability of the program, such as implementing the proxy design pattern.
Copy code The code is as follows:
//Human interface
interface IHuman
{
function GetName();
}
//Male human, implements human interface
class ManClass implements IHuman
{
//Get name method
public function GetName ()
{
return "I'm man."."
";
}
}
//Female human, implements human interface
class WomanClass implements IHuman
{
//Get name method
public function GetName()
{
return "I'm Woman."."
";
}
}
//Class factory, produce different instance objects as needed and return
class ManFactory
{
//Get instance objects according to parameters
public function GetIHuman($IHuman="man")
{
if($IHuman=="woman")
{
return new WomanClass();
}
else if($IHuman=="man")
{
return new ManClass();
}
else
{
return null;
}
}
//Get the woman class directly
public function GetWoman()
{
return new WomanClass();
//return new ManClass();
}
//Get the man class directly
public function GetMan()
{
return new ManClass();
}
}
$ManFactory=new ManFactory();
$ManClass=$ManFactory->GetIHuman();
echo $ManClass->GetName();
$IHuman=$ManFactory->GetIHuman("woman");
echo $IHuman->GetName();
$Woman=$ManFactory-> ;GetWoman();
echo $Woman->GetName();
$Man=$ManFactory->GetMan();
echo $Man->GetName();
? >
Run result:
I'm man.
I'm Woman.
I'm Woman.
I'm man.
http://www.bkjia.com/PHPjc/325543.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325543.htmlTechArticleInterface in php can only play a role in defining constraint classes. Although it is not as intuitive as c#/java, it is based on oop's encapsulation requirements, the use of interfaces can improve the scalability of the program, such as implementing agent design models...