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

PHP面向对象编程总结

PHP面向对象编程总结

学习PHP时,面向对象编程(OOP)往往是一个重要的里程碑。PHP的OOP功能提供了一种更加模块化、可扩展和易于维护的代码结构。在本文中,我们将深入探讨PHP面向对象编程的各个方面,包括类与对象、访问控制、继承与多态、抽象类与接口、静态成员与常量、魔术方法、命名空间以及异常处理。

目录

  • PHP面向对象编程总结
    • 1. 类与对象
      • Example
    • 2. 访问控制
      • Example
    • 3. 继承与多态
      • Example
    • 4. 抽象类与接口
      • Example
    • 5. 静态成员与常量
      • Example
    • 6. 魔术方法
      • Example
    • 7. 命名空间
      • Example
    • 8. 异常处理
      • Example
    • 9. 综合案例

1. 类与对象

  • 类(Class):定义对象的模板,包含属性和方法。
  • 对象(Object):类的实例化,具体的实体。
class MyClass {// 属性public $property;// 方法public function method() {// 方法体}
}$obj = new MyClass();

Example

<?php
class MyClass {public $property;public function method() {return "Hello, I'm a method!";}
}$obj = new MyClass();
$obj->property = "I'm a property.";
echo $obj->method(); // 输出: Hello, I'm a method!
echo $obj->property; // 输出: I'm a property.
?>

2. 访问控制

  • 公有(public):可在类的内部和外部访问。
  • 私有(private):仅在类的内部访问。
  • 受保护(protected):仅在类的内部和子类中访问。
class MyClass {public $publicProperty;private $privateProperty;protected $protectedProperty;
}

Example

<?php
class MyClass {public $publicProperty;private $privateProperty;protected $protectedProperty;public function __construct() {$this->publicProperty = "Public property";$this->privateProperty = "Private property";$this->protectedProperty = "Protected property";}
}$obj = new MyClass();
echo $obj->publicProperty; // 输出: Public property
//echo $obj->privateProperty; // 错误: 无法访问私有属性
//echo $obj->protectedProperty; // 错误: 无法访问受保护属性
?>

3. 继承与多态

  • 继承(Inheritance):子类继承父类的属性和方法。
  • 多态(Polymorphism):同一种方法在不同的类中有不同的实现。
class ParentClass {// 父类方法
}class ChildClass extends ParentClass {// 子类方法
}

Example

<?php
class Animal {public function makeSound() {return "Some generic sound";}
}class Dog extends Animal {public function makeSound() {return "Woof!";}
}class Cat extends Animal {public function makeSound() {return "Meow!";}
}$dog = new Dog();
echo $dog->makeSound(); // 输出: Woof!$cat = new Cat();
echo $cat->makeSound(); // 输出: Meow!
?>

4. 抽象类与接口

  • 抽象类(Abstract Class):包含抽象方法的类,不能被实例化。
  • 接口(Interface):定义了一组方法的集合,实现类必须实现这些方法。
abstract class AbstractClass {abstract public function abstractMethod();
}interface MyInterface {public function interfaceMethod();
}

Example

<?php
abstract class Shape {abstract public function getArea();
}class Circle extends Shape {private $radius;public function __construct($radius) {$this->radius = $radius;}public function getArea() {return pi() * pow($this->radius, 2);}
}interface Printable {public function printInfo();
}class Rectangle implements Printable {private $width;private $height;public function __construct($width, $height) {$this->width = $width;$this->height = $height;}public function printInfo() {echo "Rectangle width: $this->width, height: $this->height";}
}$circle = new Circle(5);
echo "Circle area: " . $circle->getArea(); // 输出: Circle area: 78.539816339745$rectangle = new Rectangle(3, 4);
$rectangle->printInfo(); // 输出: Rectangle width: 3, height: 4
?>

5. 静态成员与常量

  • 静态成员(Static Members):属于类而不是对象,可以直接通过类名访问。
  • 常量(Constants):一旦定义就无法更改的值。
class MyClass {public static $staticProperty;const CONSTANT = 'constant value';
}

Example

<?php
class Math {public static $PI = 3.14;public static function double($number) {return $number * 2;}
}echo Math::$PI; // 输出: 3.14
echo Math::double(5); // 输出: 10
?>

6. 魔术方法

  • 构造函数(__construct):对象创建时自动调用。
  • 析构函数(__destruct):对象销毁时自动调用。
  • 其他如 __get, __set, __isset, __unset 等。
class MyClass {public function __construct() {// 构造函数}public function __destruct() {// 析构函数}
}

Example

<?php
class MyClass {public function __construct() {echo "Object created!";}public function __destruct() {echo "Object destroyed!";}
}$obj = new MyClass(); // 输出: Object created!
unset($obj); // 输出: Object destroyed!
?>

7. 命名空间

  • 命名空间(Namespace):用于解决不同类库或模块之间的命名冲突。
namespace MyNamespace;class MyClass {// 类定义
}

Example

<?php
namespace MyNamespace;class MyClass {public function hello() {return "Hello from MyNamespace!";}
}$obj = new MyClass();
echo $obj->hello(); // 输出: Hello from MyNamespace!
?>

8. 异常处理

  • 异常(Exception):运行时发生的错误或异常情况的表示。
try {// 可能发生异常的代码
} catch (Exception $e) {// 异常处理代码
}

Example

<?php
try {// 可能发生异常的代码throw new Exception("An error occurred!");
} catch (Exception $e) {// 异常处理代码echo "Exception caught: " . $e->getMessage(); // 输出: Exception caught: An error occurred!
}
?>

9. 综合案例

<?php
// 定义一个抽象类 Shape
abstract class Shape {abstract public function getArea();
}// 定义一个接口 Printable
interface Printable {public function printInfo();
}// 定义一个圆形类 Circle,继承自抽象类 Shape,并实现 Printable 接口
class Circle extends Shape implements Printable {private $radius;public function __construct($radius) {$this->radius = $radius;}public function getArea() {return pi() * pow($this->radius, 2);}public function printInfo() {echo "This is a circle with radius: $this->radius";}
}// 定义一个矩形类 Rectangle,实现 Printable 接口
class Rectangle implements Printable {private $width;private $height;public function __construct($width, $height) {$this->width = $width;$this->height = $height;}public function getArea() {return $this->width * $this->height;}public function printInfo() {echo "This is a rectangle with width: $this->width and height: $this->height";}
}// 创建一个圆形对象
$circle = new Circle(5);
echo "Circle area: " . $circle->getArea() . "\n"; // 输出: Circle area: 78.539816339745
$circle->printInfo(); // 输出: This is a circle with radius: 5echo "\n";// 创建一个矩形对象
$rectangle = new Rectangle(3, 4);
echo "Rectangle area: " . $rectangle->getArea() . "\n"; // 输出: Rectangle area: 12
$rectangle->printInfo(); // 输出: This is a rectangle with width: 3 and height: 4
?>
  • 在本例中,定义了两个形状类,一个是圆形类 Circle,另一个是矩形类 Rectangle。Circle 类继承了抽象类 Shape 并实现了接口 Printable,而 Rectangle 类则直接实现了接口 Printable。这样我们就可以通过多态的方式统一处理这两种形状类的对象,并调用它们各自的方法。






每一个不曾起舞的日子,都是对生命的辜负。

相关文章:

  • Flutter 中的 SliverCrossAxisGroup 小部件:全面指南
  • C++ 变量的声明和初始化方式
  • <Rust><iced>基于rust使用iced库构建GUI实例:动态改变主题色
  • 使用Spring的@Scheduled注解实现定时任务
  • 关于高版本 Plant Simulation 每次保存是 提示提交comm对话框的处理方法
  • 使用axios+vue在离开页面时中断网络请求
  • MATLAB算法实战应用案例精讲-【数模应用】Turf组合模型(附MATLAB、python和R语言代码实现)
  • Outpainting Inpainting
  • RTA GMH系列 SERIE MOTION电机驱动板手侧 英文版
  • 【Web API DOM03】事件监听
  • VRRP
  • 创新指南|领导者如何评估自己的表现——麦肯锡专有的CEO卓越评估工具
  • 淘宝api接口是什么意思?api接口申请资格是什么?
  • echarts绘制三维柱状图
  • WordPress中借助Table of Contents Plus+Widget Options插件,实现仅在文章侧边栏显示文章目录的功能
  • 「面试题」如何实现一个圣杯布局?
  • Android 初级面试者拾遗(前台界面篇)之 Activity 和 Fragment
  • Babel配置的不完全指南
  • CentOS学习笔记 - 12. Nginx搭建Centos7.5远程repo
  • CSS 三角实现
  • github指令
  • node学习系列之简单文件上传
  • rabbitmq延迟消息示例
  • Redis 中的布隆过滤器
  • Ruby 2.x 源代码分析:扩展 概述
  • Traffic-Sign Detection and Classification in the Wild 论文笔记
  • Travix是如何部署应用程序到Kubernetes上的
  • 工作踩坑系列——https访问遇到“已阻止载入混合活动内容”
  • 汉诺塔算法
  • 前端_面试
  • 如何在 Intellij IDEA 更高效地将应用部署到容器服务 Kubernetes ...
  • 我们雇佣了一只大猴子...
  • ​软考-高级-信息系统项目管理师教程 第四版【第14章-项目沟通管理-思维导图】​
  • # windows 安装 mysql 显示 no packages found 解决方法
  • #if 1...#endif
  • (delphi11最新学习资料) Object Pascal 学习笔记---第5章第5节(delphi中的指针)
  • (Python第六天)文件处理
  • (博弈 sg入门)kiki's game -- hdu -- 2147
  • (初研) Sentence-embedding fine-tune notebook
  • (附源码)springboot 基于HTML5的个人网页的网站设计与实现 毕业设计 031623
  • (三)SvelteKit教程:layout 文件
  • (学习日记)2024.01.09
  • (学习日记)2024.02.29:UCOSIII第二节
  • (一)Linux+Windows下安装ffmpeg
  • (转)详解PHP处理密码的几种方式
  • (转贴)用VML开发工作流设计器 UCML.NET工作流管理系统
  • (最全解法)输入一个整数,输出该数二进制表示中1的个数。
  • .NET 4.0中使用内存映射文件实现进程通讯
  • .NET/C# 项目如何优雅地设置条件编译符号?
  • .net中生成excel后调整宽度
  • :中兴通讯为何成功
  • @JsonSerialize注解的使用
  • @RequestMapping处理请求异常
  • @RequestParam,@RequestBody和@PathVariable 区别
  • [5] CUDA线程调用与存储器架构