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. There are three types visibility a property can have are public, private, and protected. Public properties are ones that directly accessible by 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. Notes: Any methods created without a specific declared visibility default to public. Keep in mind that all non-method properties must be declared public, private, or protected.
<?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.