How To Declaring Properties


It is not necessary to explicitly declare properties within classes, as they can be implicitly
defined when first used. To illustrate this, in Example 5-19 the class User has no properties
and no methods but is legal code.
Example 5-19. Defining a property implicitly
<?php
$object1 = new User();
$object1->name = "Alice";
echo $object1->name;
class User {}
?>
This code correctly outputs the string Alice without a problem, because PHP implicitly
declares the variable $object1->name for you. But this kind of programming can lead
to bugs that are infuriatingly difficult to discover, because name was declared from outside
the class.
To help yourself and anyone else who will maintain your code, I advise that you get into
the habit of always declaring your properties explicitly within classes. You’ll be glad you
did.
Also, when you declare a property within a class, you may assign a default value to it.
The value you use must be a constant and not the result of a function or expression.
Example 5-20 shows a few valid and invalid assignments.
Example 5-20. Valid and invalid property declarations
<?php
class Test
{
public $name = "Paul Smith"; // Valid
public $age = 42; // Valid
public $time = time(); // Invalid - calls a function
public $score = $level * 2; // Invalid - uses an expression
}
?>
banner
Previous Post
Next Post