2024-07-23

PHP OOP 概念:类、对象和继承

php oop 概念:类、对象和继承

php 中的类

php 中的类是定义对象的属性和行为的蓝图或模板。它是一种封装数据和操作该数据的函数的方法。类定义了对象的结构和行为,包括其属性(数据)和方法(函数)。

<?php class employee {
  public $name;
  public $salary;

  public function __construct($name, $salary) {
    $this->name = $name;
    $this-&gt;salary = $salary;
  }

  public function getdetails() {
    echo "name: $this-&gt;name, salary: $this-&gt;salary";
  }
}
登录后复制

php 中的对象

php中的对象是类的实例,它代表现实世界的实体或概念。它有自己的一组属性(数据)和方法(函数)来描述和定义其行为。对象是从类创建的,可以独立操作。

$manager = new manager();
$developer = new developer();
登录后复制

php 中的继承

php 中的继承是一种允许一个类继承另一个类的属性和行为的机制。继承类(子类或子类)继承父类的所有属性和方法,还可以添加新的属性和方法或覆盖从父类继承的属性和方法。

//inheritance 

class manager extends employee {
  public $department;

  public function __construct($name, $salary, $department) {
    parent::__construct($name, $salary);
    $this-&gt;department = $department;
  }

  public function getdetails() {
    parent::getdetails();
    echo ", department: $this-&gt;department";
  }
}

class developer extends employee {
  public $specialty;

  public function __construct($name, $salary, $specialty) {
    parent::__construct($name, $salary);
    $this-&gt;specialty = $specialty;
  }

  public function getdetails() {
    parent::getdetails();
    echo ", specialty: $this-&gt;specialty";
  }
}

// create objects
$manager = new manager("john doe", 80000, "marketing");
$developer = new developer("jane smith", 70000, "front-end");

// access properties and methods
echo "manager details: ";
$manager-&gt;getdetails();
echo "/n";
echo "developer details: ";
$developer-&gt;getdetails();
登录后复制

每个类都有姓名和薪水等属性,以及 getdetails 等方法。代码从这些类创建对象并使用它们的属性和方法。在这里我们可以看到类如何继承和添加新功能,以及对象如何用于存储和显示数据。我们可以通过在当前控制台中运行该项目来检查这段代码的输出,输出将是:

Manager Details: Name: John Doe, Salary: 80000, Department: Marketing
Developer Details: Name: Jane Smith, Salary: 70000, Specialty: Front-end
登录后复制

希望你已经清楚地理解了

以上就是PHP OOP 概念:类、对象和继承的详细内容,更多请关注php中文网其它相关文章!

https://www.php.cn/faq/895254.html

发表回复

Your email address will not be published. Required fields are marked *