php 函数或者方法预设接口类型 运行时类型检查

<?php

interface IUser 

{ 

	function getName(); 

	function setName($_name); 

	function getDiscount(); //此处添加了一个抽象的方法

} 



 

class VipUser implements IUser 

{ 

	private $name; 

	private $discount = 0.8; //折扣变量 



	function getName() { 

		return $this->name; 

	} 



	function setName($_name) { 

		$this->name = $_name; 

	} 

	function getDiscount() { 

		return $this->discount; 

	} 



} 



class GoodUser implements IUser 

{ 

	private $name; 

	private $discount = 0.7; //折扣变量 



	function getName() { 

		return $this->name; 

	} 



	function setName($_name) { 

		$this->name = $_name; 

	} 

	function getDiscount() { 

		return $this->discount; 

	} 



} 





error_reporting(-1);

$v = new VipUser;

$g=new GoodUser;

//echo $v->getDiscount();



 



test($v);//ok

test($g);//ok

test("d");// error !;Catchable fatal error: Argument 1 passed to test() must implement interface IUser, string given, 



function test(IUser $p)

{

	echo $p->getDiscount();



}





 

你可能感兴趣的:(PHP)