public
private
protected
One interesting thing to note is that each method and property can have an associated level of visibility, which enables information-hiding. The three types of visibility are public, private, and protected.
- Public properties are ones that directly accessible in the instantiated object.
- Private properties cannot be accessed anywhere except from within the class. This allows one to create a public interface, where some critical internal state can be protected.
- We will discuss the protected visibility later as it's dependent upon understanding inheritance.
Any methods created without a specific declared visibility default to public. Keep in mind that properties must be declared public, private, or protected, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value (must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated).
<?php
class Person {
private $name;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
$person = new Person();
$person->name = 'error'; // This will error out because it's a private property
$person->setName('Alice');
echo $person->getName(); // Alice
- Expand the previous “Person” class, add
setName()
,getName()
methods. - Add a height property, and a getter and setter.
- Declare the correct “visibility” for each property and method.
- Invoke
var_dump()
on the person object to inspect it.