Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
In this video, we'll take a closer look at how the "scope" or "visibility" affect method access.
get_object_vars() - will only return the properties that can be accessed from the current scope. Therefore, it cannot access private or static properties of a child class.
Option 1: Adjust Visibility
From the video we adjusted the visibility to control which properties are used.
protected $description; // accessible
protected static $allowed_tags; // not accessible
Option 2: Extend Method
To extend the parent function, we would have to merge the arrays from the parent and the child. We still need to make sure that the visibility is correct, $allowed_tags would still need to be "static".
public function toArray()
{
return array_merge(
parent::toArray(),
get_object_vars($this)
);
}
Option 3: Manual Properties
We could use the getters to manually return the object properties as an array. This would give us precise control over what is returned, but this also increases the amount of manual work.
public function toArray() {
$array['id'] = $this->getId();
$array['title'] = $this->getTitle();
$array['website'] = $this->getWebsite();
$array['email'] = $this->getEmail();
$array['twitter'] = $this->getTwitter();
return $array;
}
We would then need to extend this class for the child.
public function toArray() {
parent::toArray();
$array['description'] = $this->getDescription();
return $array;
}
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up