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();
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();
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中实现重载构造函数的方法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站