Bruno
Bruno

Reputation: 458

Php abstract class constructor

There's some way to initialize the properties of an abstract class in php like this example in java?

public abstract class Person
{

    private String name;

    public Person(String name)
    {
        this.name = name;
    }
}

public class Client extends Person
{
    public Client(String name)
    {
        super(name);
    }
}

Here's my actual code : I'm getting this error : "Variable $name seems to be uninitialized"

abstract class Person
{
    private $name;

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

class Client extends Person
{
    private $name;
    public function Client($name)
    {
        parent::Person($name);
    }

}

Upvotes: 0

Views: 2822

Answers (2)

Whirlwind
Whirlwind

Reputation: 13675

One thing you should be aware of except of what is pointed in comments and in @Ali Torabi's answer, is that constructor from parent class is not called implicitly when child class constructor is called.

From the docs:

In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.

abstract class Person {
    function __construct() {
        echo 'Person constructor called<br/>';
    }
}

class Client extends Person {
    function __construct() {
        parent::__construct();
        echo 'Client constructor called<br/>';
    }
}

I guess this is important to note, because in some languages parent constructors are called automatically. Also $name variable should be protected IMO if you want it available in all classes that extending Person class. Using private keyword make a property available only within class where is defined.

Upvotes: 3

Alex
Alex

Reputation: 713

Remove $ from your class variable

$this->$name = $name;

totally wrong, try:

$this->name = $name;

Upvotes: 4

Related Questions