Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

几个PHP面向对象小实例

作者:狂刀血斧   发布日期:2024-07-17   浏览:590

  1. 创建一个名为Person的类,该类具有name和age属性,并具有一个greet方法,用于打印出问候语。
class Person {
    private $name;
    private $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }

    public function greet() {
        echo "Hello, my name is " . $this->name . " and I am " . $this->age . " years old.";
    }
}

$person = new Person("John", 25);
$person->greet();
  1. 创建一个名为Rectangle的类,该类具有width和height属性,并具有一个计算面积的方法。
class Rectangle {
    private $width;
    private $height;

    public function __construct($width, $height) {
        $this->width = $width;
        $this->height = $height;
    }

    public function calculateArea() {
        return $this->width * $this->height;
    }
}

$rectangle = new Rectangle(10, 5);
echo "The area of the rectangle is: " . $rectangle->calculateArea();
  1. 创建一个名为Car的类,该类具有brand和color属性,并具有一个加速的方法。
class Car {
    private $brand;
    private $color;
    private $speed = 0;

    public function __construct($brand, $color) {
        $this->brand = $brand;
        $this->color = $color;
    }

    public function accelerate($speed) {
        $this->speed += $speed;
        echo "The " . $this->color . " " . $this->brand . " is now traveling at " . $this->speed . " km/h.";
    }
}

$car = new Car("Toyota", "red");
$car->accelerate(50);

上一篇:PHP魔术函数__autoload的用法与一些问题

下一篇:在PHP中实现重载构造函数的方法

大家都在看

php session用法

php 定义常量

phpisset函数

php后端

php爬虫框架

php读取csv文件

php 三元表达式

php文件加密

php 拆分字符串

php pcntl

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站