PHP5 OOP新手快速入门例子

来源:互联网 发布:js菜单栏滑动 编辑:程序博客网 时间:2024/04/29 04:16
PHP5 的OOP是个好东西,最近找了些小资料给新手培训和给朋友看,还是老外的东西好,例子短小,有OOP基础的话,一看就
明白了

  1)基本的类和实例
   
<?phpclass 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
<?phpclass 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)构造函数
   <?phpclass 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  使用继承
   <?phpclass 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 
       <?phpclass 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  访问父类中的被覆盖的方法
    <?phpclass 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();?>