当前位置:Gxlcms > PHP教程 > PHP 高级课程笔记 面向对象

PHP 高级课程笔记 面向对象

时间:2021-07-01 10:21:17 帮助过:11人阅读

例一:
代码如下:
<?php
// 类的定义
class User
{
// 属性,注意public、private、protected的作用范围
public $name = "hackbaby";
// 构造函数
function __construct()
{
echo "construct<br />";
}
// 方法
function say()
{
echo "这是在类的本身调用:$this->name";
}
// 析构函数
function __destruct()
{
echo "destruct";
}
// 返回当前对象的描述信息 通过实例化的变量名调用例如本例中的$user
function __toString()
{
return "user class";
}
}
//实例化,如果构造函数有参数则用$user = new User('参数');
$user = new User();
echo $user->name . "<hr />";
$user->say();
echo "<hr />";
echo $user;
?>

例二:

代码如下:
<?php
class Fruit
{
protected $fruit_color;
protected $fruit_size;

function setcolor($color)
{
$this->fruit_color = $color;
}

function getcolor()
{
return $this->fruit_color;
}

function setsize($size)
{
$this->fruit_size = $size;
}

function getsize()
{
return $this->fruit_size;
}

function save()
{
//代码
}
}
class apple extends Fruit
{
private $variety;

function setvariety($type)
{
$this->variety = $type;
}

function getvariety()
{
return $this->variety;
}
}
$apple = new apple();
echo $apple->setvariety('红富士');
echo $apple->getvariety();
echo "<br />";
echo $apple->setcolor('red');
echo $apple->getcolor();
echo "<br />";
echo $apple->setsize('特大');
echo $apple->getsize();

?>

人气教程排行