PHP5 的OOP是个好东西,最近找了些小资料给新手培训和给朋友看,还是老外的东西好,例子短小,有OOP基础的话,一看就
明白了
1)基本的类和实例
明白了
1)基本的类和实例
<?php
class Animal
{
var $name;
function set_name($text)
{
$this->name = $text;
}
function get_name()
{
return $this->name;
}
}
$lion = new Animal;
$lion->set_name("Leo");
echo "The name of your new lion is ", $lion->name, ".";
?>
2) 加上些访问控制符,如private
<?php class Animal { private $name; function set_name($text) {$this->name = $text;} function get_name() {return $this->name;} } $lion = new Animal; $lion->set_name("Leo"); echo "The name of your new lion is ", $lion->name, "."; ?>由于用了privae,所以这里是出错了,要用get_name去访问3)构造函数<?php class Animal { var $name; function __construct($text) { $this->name = $text; } function set_name($text) { $this->name = $text; } function get_name() { return $this->name; } } $lion = new Animal("Leo"); echo "The name of your new lion is ", $lion->get_name(), "."; ?> 用 _ _construct()做构造函数( 注意,是两个紧跟着的_)4 使用继承<?php class Animal { var $name; function set_name($text) { $this->name = $text; } function get_name() { return $this->name; } } class Lion extends Animal { var $name; function roar() { echo $this->name, " is roaring!<BR>"; } } echo "Creating your new lion...<BR>"; $lion = new Lion; $lion->set_name("Leo"); $lion->roar(); ?>5 Overriding<?php class animal { var $name; function set_name($text) { $this->name = $text; } function get_name() { return $this->name; } } class Lion extends Animal { var $name; function roar() { echo $this->name, " is roaring!<BR>"; } function set_name($text) { $this->name = strtoupper($text); } } echo "Creating your new lion...<BR>"; $lion = new Lion; $lion->set_name("Leo"); $lion->roar(); ?>输出:LEO is roaring这时子类覆盖了父类的set_name方法了6 访问父类中的被覆盖的方法<?php class Animal { var $name; function set_name($text) { $this->name = $text; } function get_name() { return $this->name; } } class Lion extends Animal { var $name; function roar() { echo $this->name, " is roaring!<BR>"; } function set_name($text) { Animal::set_name($text); } } echo "Creating your new lion...<BR>"; $lion = new Lion; $lion->set_name("Leo"); $lion->roar(); ?>