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

PHP高级课程笔记面向对象_php技巧

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

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

例二:

代码如下:
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 "
";
echo $apple->setcolor('red');
echo $apple->getcolor();
echo "
";
echo $apple->setsize('特大');
echo $apple->getsize();

?>

人气教程排行