<?php class Car { public $color = 'red'; public function getColor() { return $this->color; } } $car = new Car(); echo $car->getColor(); ?>
The method getColor() returns the $color property of the current object using $this->color. Since $color is set to 'red', the output is 'red'.
<?php class Person { public $name = 'Alice'; public function sayName() { return name; } } $p = new Person(); echo $p->sayName(); ?>
Inside the method, name without $this-> is treated as a constant. Since no constant named 'name' exists, PHP throws an error.
setAge method not change the $age property of the object?<?php class User { public $age = 20; public function setAge($age) { $age = $age; } } $user = new User(); $user->setAge(30); echo $user->age; ?>
The method assigns the parameter $age to itself, which does nothing. To update the object's property, it should use $this->age = $age;.
$name property inside a method?<?php class Animal { public $name = 'Dog'; public function getName() { // return statement here } } ?>
To access an object property inside a method, use $this->propertyName. Other options have syntax errors or incorrect variable usage.
<?php class Builder { private $text = ''; public function addHello() { $this->text .= 'Hello '; return $this; } public function addWorld() { $this->text .= 'World!'; return $this; } public function getText() { return $this->text; } } $b = new Builder(); echo $b->addHello()->addWorld()->getText(); ?>
Each method appends text and returns $this, allowing chaining. The final getText() returns the full string 'Hello World!'.
