Why This Happens
Protected properties are only accessible within the class and its subclasses. External code cannot read or write them directly. This encapsulation is intentional. Use public getter and setter methods to provide controlled access to protected properties.
The Problem
class User {
protected string $password;
public function __construct(string $password) {
$this->password = password_hash($password, PASSWORD_DEFAULT);
}
}
$user = new User('secret');
echo $user->password; // Cannot access protected propertyThe Fix
class User {
protected string $password;
public function __construct(string $password) {
$this->password = password_hash($password, PASSWORD_DEFAULT);
}
public function verifyPassword(string $password): bool {
return password_verify($password, $this->password);
}
}
$user = new User('secret');
if ($user->verifyPassword('secret')) {
echo 'Authenticated';
}Step-by-Step Fix
- 1
Understand the visibility
The property is protected intentionally. Determine if you should access it directly or through a method.
- 2
Use a getter method
Create a public method that provides controlled access to the property value.
- 3
Change visibility if needed
If the property genuinely needs to be publicly accessible, change protected to public. But prefer methods for encapsulation.
Got the actual stack trace?
Paste it into our free AI explainer to get the cause and the fix for your specific case — no signup, nothing to install.
Explain my errorBugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free