Defining properties
Learn to define properties inside a class and give default values.
Defining properties
A property is a variable stored inside a class. A property is defined with a visibility keyword (e.g. public) and a variable name starting with $.
Example: public $title = "Unknown";. Here public means the property can be accessed from outside, $title is the variable name and "Unknown" is the default value. The default value is optional; if omitted, the property is null at first.
Default value and visibility
Giving a property a default value provides ready initial data when an instance is created. The default must be a constant; it cannot be a variable or function call.
Besides public there are private and protected visibilities. We will only use public in this lesson; the others come later. A public property can be accessed from outside the class too.
Exercise Add a property to the Book class
Define a class named Book. Add the property public $title = "Unknown"; inside it. After the class, write echo "Book class ready" . "\n";.
Show example solution
Inside class Book { } add public $title = "Unknown";, then echo.
Example solution:
<?php
// Define the Book class and the $title property
class Book {
public $title = "Unknown";
}
echo "Book class ready" . "\n";
Test yourself
-
Complete the property definition
class Book { ____ $title = "Unknown"; }Show answer
class Book { public $title = "Unknown"; } -
Which is a valid property definition inside a class?
- $title = "Unknown";
- property $title = "Unknown";
- public $title = "Unknown";
- var title = "Unknown";
Show answer
public $title = "Unknown"; — Correct. The public visibility, the $title variable and a default value form a property.
-
Match the parts of a property
- public
- Visibility
- $title
- Property variable
- "Unknown"
- Default value