Saturday, March 24, 2007

Object Interfaces

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.
Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.

All methods declared in an interface must be public, this is the nature of an interface.
在Interface里定义的方法必须都是public的,这是Interface的特点。在abstract class 中方法可以是其他二种属性。

To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.
Note: A class cannot implement two interfaces that share function names, since it would cause ambiguity.
class 实现一个interface用implements操作符,Interface中所有定义的方法在class中都必须实现,这点与abstract class 一样,如果class中有个方法没有实现的话会报错,错误性质与abstract class一样。

interface anInterface
public function getVar($name, $age);
public function getHtml($html);

class ImplementInterface implements anInterface
public function getVar($name, $age)
echo "name is: {$name}", " age is : {$age}", "<br>";
public function getHtml($html)
echo "<pre>";
echo "</pre>";

$i = new ImplementInterface();
$i->getVar("yu", 29);
$i->getHtml("<a href='#'> test a href </a>");

定义一个interface一般习惯以小写字母开始,命名同变量命名,class 和 abstract class 定义是名字首字母习惯大写开始。

No comments :