PHP 高级课程笔记 面向对象
程序员文章站
2022-04-28 21:19:22
例一: 复制代码 代码如下:
例一:
<?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();
?>
复制代码 代码如下:
<?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();
?>
上一篇: PHP 七大优势分析
下一篇: 芝奇推藏礼盒:插上皇家戟内存闪耀钻石光芒