I'm trying to add Final
keyword in db
class for prevent the some query functions in other classes. But this final keyword giving me fatal error.
Fatal error: Class user may not inherit from final class (db)
final class db{
private $connection;
public function __construct () {
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'studentsyetem';
$this->connection = new mysqli($host, $username, $password, $dbname);
if ($this->connection->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
echo 'Connected';
}
}
public function insert($u_name,$u_password,$u_level){
$sql = "INSERT INTO users (u_name, u_password, u_level, date_added) VALUES ('".$u_name."', '".$u_password."', '".$u_level."', '".date("Y-m-d H:i:s")."')";
mysqli_query($this->connection,$sql);
}
}
class user extends db{
public function child() {
echo 'user';
}
}
$user = new user();
echo $user->child();
Without final
keyword code working fine, I wanted to know where i'm doing wrong. Can any one guide me I will appreciate.
Classes with Final Keyword cannot be inherited. Any child class should not inherit final class.
Just to show you an example it explans why the error occurs. final
method cannot be overwritten, nor can you with abstract
nor extends
BUT with trait
.
class foo {
final public function Func() {
echo "foo::Func() created";
}
}
class bar extends foo {
public function Func() {
echo "foo::Func() re-written"; // it fails
}
}