Ejemplo n.º 1
0
class SUV extends Car
{
    public $has4WD = false;
    // child classes can override parent properties
    public function getStatus()
    {
        // child classes can still access parent methods using parent::
        return parent::getStatus();
    }
}
$myCar = new Car('Mercedes', '760GL', 'black');
echo '<p>The color of my car is ' . $myCar->color . '.</p>';
$yourCar = new SUV('Hummer', 'H2', 'red');
echo '<p>The color of your car is ' . $yourCar->color . '.</p>';
echo '<p>My car status is ' . $myCar->getStatus() . '</p>';
$myCar->startEngine();
echo '<p>My car status is ' . $myCar->getStatus() . '</p>';
//$yourCar->startEngine();
echo '<p>Your car status is ' . $yourCar->getStatus() . '</p>';
echo '<p>Your car ' . (empty($yourCar->has4WD) ? 'does not' : 'does') . ' have 4WD.</p>';
echo '<p>My car ' . (empty($myCar->has4WD) ? 'does not' : 'does') . ' have 4WD.</p>';
echo '<p>Say something: ' . Car::saySomething() . '</p>';
// works but not recommended
echo $myCar::saySomething();
echo $myCar->saySomething();
?>



</body>
</html>
Ejemplo n.º 2
0
<?php

class Car
{
    public $color;
    public $make;
    public $model;
    public $status = 'off';
    public function startEngine()
    {
        // sets the valus of $status in the instance
        $this->status = 'running';
    }
}
// create an instance of the Car class
$myCar = new Car();
$myCar->color = 'black';
$myCar->make = 'Mercedes';
$myCar->model = '760 Series';
echo '<p>' . $myCar->color . '</p>';
echo '<p>' . $myCar->status . '</p>';
$yourCar = new Car();
$yourCar->color = 'red';
$yourCar->startEngine();
echo '<p>' . $yourCar->status . '</p>';
echo '<p>' . $myCar->status . '</p>';