PHP
Classes and Inheritance in PHP
Define classes with constructors, visibility, and inheritance in PHP.
By EZ4Code Team
classoopintermediate
Code
<?php
class User {
private string $name;
private int $age;
public function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
public function getName(): string {
return $this->name;
}
public function isAdult(): bool {
return $this->age >= 18;
}
}
// Inheritance
class Admin extends User {
private array $permissions = [];
public function grant(string $perm): void {
$this->permissions[] = $perm;
}
}
$admin = new Admin("Alice", 30);
$admin->grant("delete");
echo $admin->getName(); // Alice
echo $admin->isAdult(); // 1 (true)Explanation
Defines a class with typed properties, a constructor for initialization, and public methods controlling access to private state. Inheritance via extends reuses the parent constructor and methods, with visibility (private/protected/public) enforcing encapsulation. Admin extends User to add role-specific behavior like permission management.
More PHP Snippets
Arrays and Array Functions in PHP
Create indexed, associative, and multidimensional arrays with map and filter.
String Functions in PHP
Manipulate strings with substr, replace, explode, and sprintf in PHP.
Read and Write Files in PHP
Read, write, append, and iterate files with PHP filesystem functions.
PDO Database Queries in PHP
Connect and run prepared statements safely with PDO in PHP.
Sessions and Cookies in PHP
Store user data across requests with sessions and cookies in PHP.