Problem in Class please help

Would you please explain me what we will call ‘$this->name’ in construct ??


class Person {
    private $name;

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

    public function getName() {
        return $this->name;
    }

    public function getTitle() {
        return $this->getName()." the person";
    }

    public function sayHello() {
        echo "Hello, I'm ".$this->getTitle()."<br/>";
    }

    public function sayGoodbye() {
        echo "Goodbye from ".self::getTitle()."<br/>";
    }
}

class Geek extends Person {
    public function __construct($name) {
        parent::__construct($name);
    }

    public function getTitle() {
        return $this->getName()." the geek";
    }
}

$geekObj = new Geek("Ludwig");
//$geekObject = new Person("Ludwig");
//$geekObject->sayHello();
$geekObj->sayHello();
$geekObj->sayGoodbye();

Thank for your help in advance.

It’s a class property (also called a member variable).

Thanks fretburner

So this property can be made in any of function in class and can be called like constructor? or this is specific to constructor.

You can access class properties from any method of the class, not just the constructor. If you look at the example code you posted, you can see that the getName() method also uses the name property.

If you declare a class property as public, it can also be accessed from outside of the object:


class Person 
{
    public $name;

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

$person = new Person('Fred');

echo $person->name;  // Outputs 'Fred'

Thanks fretburner,

There was a little confusion, now clear…:slight_smile:

Thanks again.