Bird
0
0

You want to declare a PHP class Book with a property $title initialized to "PHP Basics" and a method getTitle() that returns the title. Which is the correct class declaration?

hard📝 Application Q15 of 15
PHP - Classes and Objects
You want to declare a PHP class Book with a property $title initialized to "PHP Basics" and a method getTitle() that returns the title. Which is the correct class declaration?
Aclass Book { public $title; public function getTitle() { return $title; } }
Bclass Book { public $title = "PHP Basics"; function getTitle() { return title; } }
Cclass Book { public $title = "PHP Basics"; public function getTitle() { return $this->title; } }
Dclass Book { public $title = "PHP Basics"; public function getTitle() { return $Book->title; } }
Step-by-Step Solution
Solution:
  1. Step 1: Declare property with initial value

    Property $title is declared public and initialized to "PHP Basics" correctly in class Book { public $title = "PHP Basics"; public function getTitle() { return $this->title; } }.
  2. Step 2: Define method returning property

    Method getTitle() must return $this->title to access the object's property. class Book { public $title = "PHP Basics"; public function getTitle() { return $this->title; } } does this correctly.
  3. Step 3: Check other options for errors

    class Book { public $title = "PHP Basics"; function getTitle() { return title; } } returns title without $this->, class Book { public $title; public function getTitle() { return $title; } } returns $title which is undefined in method scope, class Book { public $title = "PHP Basics"; public function getTitle() { return $Book->title; } } uses $Book->title which is invalid inside class.
  4. Final Answer:

    class Book { public $title = "PHP Basics"; public function getTitle() { return $this->title; } } -> Option C
  5. Quick Check:

    Use $this->property inside methods [OK]
Quick Trick: Use $this->property to access inside methods [OK]
Common Mistakes:
  • Returning property without $this-> inside method
  • Using variable names without $this->
  • Trying to access property with class name variable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes