PHP Curso

PHP Classes, Objects, and Inheritance

Tutorial de Python 3 para iniciantes.

Defining a Class

<?php
class Animal {
    // Properties
    public string $name;
    protected int $age;
    private string $species;

    // Constructor
    public function __construct(string $name, int $age, string $species) {
        $this->name = $name;
        $this->age = $age;
        $this->species = $species;
    }

    // Method
    public function describe(): string {
        return "{$this->name} is a {$this->species}, age {$this->age}";
    }
}

$dog = new Animal("Rex", 3, "dog");
echo $dog->describe(); // Rex is a dog, age 3

Inheritance

<?php
class Dog extends Animal {
    private string $breed;

    public function __construct(string $name, int $age, string $breed) {
        parent::__construct($name, $age, "dog");
        $this->breed = $breed;
    }

    // Override parent method
    public function describe(): string {
        return parent::describe() . " ({$this->breed})";
    }

    public function bark(): string {
        return "{$this->name} says: Woof!";
    }
}

$rex = new Dog("Rex", 3, "Labrador");
echo $rex->describe(); // Rex is a dog, age 3 (Labrador)
echo $rex->bark();     // Rex says: Woof!

Interfaces

<?php
interface Drawable {
    public function draw(): string;
    public function getArea(): float;
}

class Circle implements Drawable {
    public function __construct(private float $radius) {}

    public function draw(): string {
        return "Drawing circle with radius {$this->radius}";
    }

    public function getArea(): float {
        return M_PI * $this->radius ** 2;
    }
}

$c = new Circle(5.0);
echo $c->draw();                    // Drawing circle with radius 5
echo round($c->getArea(), 2);       // 78.54

Static Methods and Properties

<?php
class MathHelper {
    public static float $pi = 3.14159;

    public static function factorial(int $n): int {
        if ($n <= 1) return 1;
        return $n * self::factorial($n - 1);
    }
}

echo MathHelper::$pi;              // 3.14159
echo MathHelper::factorial(5);     // 120

Abstract Classes

<?php
abstract class Shape {
    abstract public function area(): float;

    public function describe(): string {
        return get_class($this) . " with area " . round($this->area(), 2);
    }
}

class Rectangle extends Shape {
    public function __construct(
        private float $width,
        private float $height
    ) {}

    public function area(): float {
        return $this->width * $this->height;
    }
}

$r = new Rectangle(4, 5);
echo $r->describe(); // Rectangle with area 20