PHP 5 OOP初心者快速入門例
PHP 5の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();
?>