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

类和对象

php 复制代码
<?php
//声明一个名为 Fruit 的类,它包含两个属性($name 和 $color)以及两个用于设置和获取 $name 属性的方法 set_name() 和 get_name():
class Fruit {
  // Properties
  public $name;
  public $color;

  // Methods
  function set_name($name) {
    $this->name = $name;
  }
  function get_name() {
    return $this->name;
  }
}
?>

构造函数

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

php 复制代码
<?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 复制代码
<?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 复制代码
<?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.

?>

访问修饰符

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

php 复制代码
/*
有三种访问修饰符:

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 复制代码
<?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.
?>
相关推荐
言之。1 小时前
别学了,打会王者吧
java·python·mysql·容器·spark·php·html5
帅云毅9 小时前
文件上传--解析漏洞和编辑器
笔记·学习·安全·web安全·编辑器·php
wt_cs9 小时前
身份证实名认证接口数字时代的信任基石-node.js实名认证集成
开发语言·node.js·php
胡译胡说14 小时前
PHP核心开发者Nikita的首次提交,就实现了个寂寞啊
php
老李不敲代码14 小时前
榕壹云预约咨询系统:基于ThinkPHP+MySQL+UniApp打造的灵活预约小程序解决方案
mysql·微信小程序·小程序·uni-app·php
fakaifa15 小时前
【最新版】西陆健身系统源码全开源+uniapp前端
前端·小程序·uni-app·开源·php·约课小程序·健身小程序
万岳软件开发小城19 小时前
基于PHP+Uniapp的互联网医院源码:电子处方功能落地方案
开发语言·uni-app·php·软件开发·互联网医院系统源码·智慧医院app
星云ai19 小时前
矩阵运营的限流问题本质上是平台与创作者之间的流量博弈
服务器·网络·php
会讲英语的码农1 天前
php基础
开发语言·后端·php
天若有情6731 天前
用 C++ 模拟 Axios 的 then 方法处理异步网络请求
网络·c++·php