To add data to a class, properties, or class-specific variables, are used. These work exactly like regular variables, except they're bound to the object and therefore can only be accessed using the object.


To add a property to MyClass, add the following code to your script:
<?php
class MyClass
{
  public $prop1 = "I'm a class property!";
}
$obj = new MyClass;
var_dump($obj);
?>
The keyword public determines the visibility of the property, which you'll learn about a little later in this chapter. Next, the property is named using standard variable syntax, and a value is assigned (though class properties do not need an initial value).
To read this property and output it to the browser, reference the object from which to read and the property to be read:
echo $obj->prop1;
Because multiple instances of a class can exist, if the individual object is not referenced, the script would be unable to determine which object to read from. The use of the arrow (->) is an OOP construct that accesses the contained properties and methods of a given object.
Modify the script in test.php to read out the property rather than dumping the whole class by modifying the code as shown:
<?php
class MyClass
{
  public $prop1 = "I'm a class property!";
}
$obj = new MyClass;
echo $obj->prop1; // Output the property
?>
Reloading your browser now outputs the following:
I'm a class property!

Post a Comment

 
Top