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.
?>
相关推荐
90后小陈老师16 分钟前
PHP 配置默认值失效排查实录:isset 兜底遇上表单空串回填,首页文案是怎么集体消失的
开发语言·php
AC赳赳老秦5 小时前
OpenClaw 多源采集公开行业数据:从原始信息到研究报告初稿的自动化实践
java·c语言·c++·python·php·deepseek·openclaw
想要成为老金高手10 小时前
Nginx、PHP、Memcache、Tomcat 与 OpenResty 实验汇总
nginx·php·memcached
新鲜势力呀10 小时前
深入理解 Elliot CUDA 编程核心:PHP 实现 CUDA 并行计算思想与实践
android·开发语言·php
XR12345678811 小时前
校园网络安全组网选型:内网流量可视与设备联动,谁更稳?
服务器·web安全·php
XR12345678812 小时前
工厂办公楼无线网络:多楼层覆盖与访客体验怎么选?
开发语言·php
dog2501 天前
网络优化,还是降低各阶矩
服务器·网络·php
x_x-F1 天前
网络数据从网卡到用户态:一场基于内存所有权转移的接力赛
开发语言·网络·php
g10565591391 天前
LAMP博客平台Wordpress实战
android·mysql·nginx·php
许彰午1 天前
# allbytaskid——一个接口扛六个DataStore
运维·服务器·php