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.
?>
相关推荐
Q_Q5110082856 分钟前
python的软件工程与项目管理课程组学习系统
spring boot·python·django·flask·node.js·php·软件工程
BingoGo1 小时前
重新学习 PHP 目前短运算符 简化你得代码
后端·php
Fine姐3 小时前
The Network Link Layer: 无线传感器中Delay Tolerant Networks – DTNs 延迟容忍网络
开发语言·网络·php·硬件架构
hotlinhao8 小时前
php版的FormCreate使用注意事项
php·crmeb
鱼鱼说测试14 小时前
Jenkins+Python自动化持续集成详细教程
开发语言·servlet·php
网硕互联的小客服19 小时前
Apache 如何支持SHTML(SSI)的配置方法
运维·服务器·网络·windows·php
苏琢玉19 小时前
如何让同事自己查数据?写一个零依赖 PHP SQL 查询工具就够了
mysql·php
全栈软件开发1 天前
PHP域名授权系统网站源码_授权管理工单系统_精美UI_附教程
开发语言·ui·php·php域名授权·授权系统网站源码
mit6.8241 天前
ubuntu远程桌面很卡怎么解决?
linux·ubuntu·php
奥格列的魔法拖鞋~2 天前
Docker-LNMP架构 创建多项目- 单个ngixn代理多个PHP容器服务
nginx·docker·eureka·架构·php·lnmp