0

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);
    }

}
2
  • 4
    Note that you should be using __construct() for your constructors in PHP classes, not the name of the class.... the latter was retained for backward compatibility with PHP 4, but is now deprecated Commented May 30, 2015 at 17:55
  • 4
    Note also that using a private property with the same name in both a child and a parent class can lead to awkward, hard-to-debug problems Commented May 30, 2015 at 17:56

2 Answers 2

4

Remove $ from your class variable

$this->$name = $name;

totally wrong, try:

$this->name = $name;
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.