欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2022-05-08 14:11:58
...
例一:
复制代码 代码如下:

// 类的定义
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();

?>
相关标签: PHP 面向对象