Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php class extends - attributes/methods with same name ok?

Tags:

php

class

extends

If you have a class named "User" and another class named "Admin" that extends "User", and you want Admin to inherit all attributes,methods from User, except for the __construct method, for example.

class User {
private $name;

function __construct($name) {
$this->name = $name;
}
}

and

class Admin extends User {
private $authorization;

function __construct($name,$authorization) {
$this->name = $name;
$this->authorization = $authorization;
}
}

Is this correct? Does Admin override User's construct method? If the extending class has the same method name I suppose it's invalid. Am I totally missing the point of class extension?

like image 995
Gal Avatar asked Sep 16 '25 03:09

Gal


1 Answers

It is not invalid. One aspect of class inheritance is, that you can override methods and provide another implementation.

But in your case, I would do

class Admin extends User {
    private $authorization;

    function __construct($name,$authorization) {
        parent::__construct($name);
        $this->authorization = $authorization;
    }
}

as you already implement the "name assignment" in the parent class. It is a cleaner approach.

like image 143
Felix Kling Avatar answered Sep 17 '25 19:09

Felix Kling