当前位置: 首页 > news >正文

PHP基础学习笔记(面向对象OOP)

类和对象

<?php
//声明一个名为 Fruit 的类,它包含两个属性($name 和 $color)以及两个用于设置和获取 $name 属性的方法 set_name() 和 get_name():
class Fruit {// Propertiespublic $name;public $color;// Methodsfunction set_name($name) {$this->name = $name;}function get_name() {return $this->name;}
}
?>

构造函数

构造函数允许您在创建对象时初始化对象的属性。

<?php
class Fruit {public $name;public $color;function __construct($name) {$this->name = $name;}function get_name() {return $this->name;}
}$apple = new Fruit("Apple");
echo $apple->get_name(); //Apple
$orange = new Fruit("Orange");
echo $orange->get_name();
?>

析构函数

当对象被破坏或脚本停止或退出时,会调用一个析构函数。
如果你创建了一个__destruct()函数,PHP会在脚本结束时自动调用这个函数。

<?php
class Fruit {public $name;public $color;function __construct($name) {$this->name = $name;}function __destruct() {echo "The fruit is {$this->name}.";}
}$apple = new Fruit("Apple"); //The fruit is Apple.
?>
<?php
class Fruit {public $name;public $color;function __construct($name, $color) {$this->name = $name;$this->color = $color;}function __destruct() {echo "The fruit is {$this->name} and the color is {$this->color}.";}
}$apple = new Fruit("Apple", "red"); //The fruit is Apple and the color is red.?>

访问修饰符

属性和方法可以有访问修饰符来控制它们的访问位置。

/*
有三种访问修饰符:public - 可以从任何地方访问属性或方法。 这是默认设置
protected - 属性或方法可以在类内以及从该类派生的类中访问
private - 属性或方法只能在类中访问
*/<?php
class Fruit {public $name;protected $color;private $weight;
}$mango = new Fruit();
$mango->name = 'Mango'; // OK
$mango->color = 'Yellow'; // ERROR
$mango->weight = '300'; // ERROR
?>

继承

子类将从父类继承所有公共和受保护的属性和方法。 此外,它还可以有自己的属性和方法。

<?php
class Fruit {public $name;public $color;public function __construct($name, $color) {$this->name = $name;$this->color = $color;}public function intro() {echo "The fruit is {$this->name} and the color is {$this->color}.";}
}// Strawberry is inherited from Fruit
class Strawberry extends Fruit {public function message() {echo "Am I a fruit or a berry? ";}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message(); //Am I a fruit or a berry? 
$strawberry->intro(); //The fruit is Strawberry and the color is red.
?>
http://www.lryc.cn/news/351325.html

相关文章:

  • Mysql超详细安装配置教程(保姆级图文)
  • HR招聘测评,如何判断候选人的团队协作能力?
  • [STM32-HAL库]Flash库-HAL库-复杂数据读写-STM32CUBEMX开发-HAL库开发系列-主控STM32F103C6T6
  • windows 下访问 csdn 异常问题
  • vue3结合element-plus之如何优雅的使用表格
  • 网络协议——Modbus-RTU
  • 【Qt】如何优雅的进行界面布局
  • 【八股系列】分别说一下nodeJS和浏览器的事件循环机制?
  • 关于基础的流量分析(1)
  • 数据结构---树,二叉树的简单概念介绍、堆和堆排序
  • MySQL聚合函数(多行函数)
  • 智慧教室课堂-专注度及考试作弊系统、课堂动态点名,情绪识别、表情识别和人脸识别结合
  • 单例模式简要介绍
  • 深度学习面试问题总结(21)| 模型优化
  • 4月手机行业线上市场销售数据分析
  • 首都师范大学聘请旅美经济学家向凌云为客座教授
  • 多电脑共享鼠标键盘
  • 展厅设计对企业有哪些作用
  • LeetCode-102. 二叉树的层序遍历【树 广度优先搜索 二叉树】
  • 基于时频模糊算子的数据增强方法
  • 浅谈后端整合Springboot框架后操作基础配置
  • 英码科技算能系列边缘计算盒子再添新成员!搭载TPU处理器BM1688CV186AH,功耗更低、接口更丰富
  • selenium 爬取今日头条
  • docker 安装 yapi
  • 【AI如何帮你编写测试用例并输出表格格式】
  • 九宫格转圈圈抽奖活动,有加速,减速效果
  • 利用阿里OSS服务给文件设置过期删除--简单版
  • LabVIEW控制Trio控制器
  • 02--大数据Hadoop集群实战
  • 【ARMv8/v9 异常模型入门及渐进 10 -- WFI 与 WFE 使用详细介绍 1】