How can encapsulation and proper object instantiation be maintained when dealing with related objects like "Mann" and "Frau" in PHP classes?
When dealing with related objects like "Mann" and "Frau" in PHP classes, encapsulation and proper object instantiation can be maintained by using inheritance. By creating a base class for both "Mann" and "Frau" with shared properties and methods, we can ensure encapsulation and avoid code duplication. Proper object instantiation can be achieved by using constructors in each subclass to initialize specific properties.
<?php
class Person {
protected $name;
protected $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
}
class Mann extends Person {
protected $beard;
public function __construct($name, $age, $beard) {
parent::__construct($name, $age);
$this->beard = $beard;
}
}
class Frau extends Person {
protected $longHair;
public function __construct($name, $age, $longHair) {
parent::__construct($name, $age);
$this->longHair = $longHair;
}
}
$mann = new Mann("Max", 30, true);
$frau = new Frau("Emma", 25, false);
?>
Related Questions
- How can differences in server environments, such as local development versus live hosting, impact the occurrence of header errors in PHP code?
- In PHP, how can a date be stored normally and only have the time difference calculated during output?
- How can you check if sessions are enabled and properly configured in PHP?