PHP5 OOP新手快速入门例子

   PHP5 的OOP是个好东西,最近找了些小资料给新手培训和给朋友看,还是老外的东西好,例子短小,有OOP基础的话,一看就
明白了

  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();
?>
 

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值