PHP object-oriented programming examples including classes, objects, inheritance, and methods.
name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');
echo $apple->get_name();
echo "
";
echo $banana->get_name();
?>
name = $name;
}
}
$apple = new Fruit();
$apple->set_name("Apple");
echo $apple->name;
?>
name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();
var_dump($apple instanceof Fruit);
?>
name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit("Apple");
echo $apple->get_name();
?>
name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}
$apple = new Fruit("Apple");
?>
name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
// Strawberry is inherited from Fruit
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message();
$strawberry->intro();
?>
name = $name;
}
abstract public function intro() : string;
}
// Child classes
class Audi extends Car {
public function intro() : string {
return "Choose German quality! I'm an $this->name!";
}
}
class Volvo extends Car {
public function intro() : string {
return "Proud to be Swedish! I'm a $this->name!";
}
}
class Citroen extends Car {
public function intro() : string {
return "French extravagance! I'm a $this->name!";
}
}
// Create objects from the child classes
$audi = new audi("Audi");
echo $audi->intro();
echo "
";
$volvo = new volvo("Volvo");
echo $volvo->intro();
echo "
";
$citroen = new citroen("Citroen");
echo $citroen->intro();
?>
msg1();
?>