PHP 编程语言手册三:面向对象的 PHP
1。类定义和构造函数+析构函数
---->[obj/Shape.php]----------------
<?php
namespace toly1994;
class Shape{
public function __construct(){
echo "Shape构造函数";
}
function __destruct(){
echo "Shape析构函数";
}
}
---->[obj/Client.php]----------------
<?php
include './Shape.php';//引入文件
use toly1994\Shape;
$shape = new Shape();
复制代码
2.类封装(成员变量、成员方法)
---->[obj/Shape.php]----------------
<?php
namespace toly1994;
class Shape{
private $name;
public function __construct($name){
echo "Shape构造函数<br/>";
$this->name = $name;
}
public function getName(){
return $this->name;
}
public function setName($name){
$this->name = $name;
}
public function draw(){
echo "绘制$this->name <br/>";
}
function __destruct(){
echo "Shape析构函数";
}
}
|-- 使用 --------------------------
$shape = new Shape("Shape");
$shape->draw();//绘制Shape
$shape->setName("四维空间<br/>");
echo $shape->getName();//四维空间
复制代码
3。类继承
---->[obj/Point.php]----------------
<?php
namespace toly1994;
class Point extends Shape{
public $x;
public $y;
}
|-- 使用 --------------------------
$point = new Point("二维点");
$point->draw();//绘制二维点
echo $point->getName();//二维点
$point->x=20;//二维点
echo $point->x;//20
复制代码
4。类的多态性
---->[obj/Circle.php]----------------
<?php
namespace toly1994;
class Circle extends Shape{
private $radius;
public function getRadius(){
return $this->radius;
}
public function setRadius($radius){
$this->radius = $radius;
}
public function draw(){
echo "Draw in Circle<br/>";
}
}
---->[obj/Point.php]----------------
<?php
namespace toly1994;
class Point extends Shape{
public $x;
public $y;
public function draw(){
echo "Draw in Point<br/>";
}
}
|-- 使用 --------------------------
$point=new Point("");
doDraw($point);//Draw in Point
$circle=new Circle("");
doDraw($circle);//Draw in Circle
function doDraw(Shape $shape){
$shape->draw();
}
复制代码
5。接口与抽象类
抽象类---->[obj/Shape.php]----------------
abstract class Shape{
...
//抽象方法
abstract protected function draw();
}
接口---->[obj/Drawable.php]----------------
<?php
namespace toly1994;
interface Drawable{
public function draw();
}
|-- 实现接口 implements 关键字-----------
include './Drawable.php';//引入文件
abstract class Shape implements Drawable
作者:张风捷特烈
链接:https://juejin.im/post/5c8a19d75188257dd56e7d91
来源:掘金
版权归作者所有。商业转载请联系作者获得许可。非商业转载请注明来源。
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。