public access
Learn that public properties and methods are accessible everywhere.
The public access modifier
When you mark a class property or method as public, it can be reached from anywhere: inside the class, from subclasses, and from outside the class. public is the widest visibility (access modifier).
In PHP 8.3 you declare a property with public string $name. From outside you read or write it as $obj->name. The legacy PHP 4 style var $name is also treated as public, but modern code prefers the explicit public keyword.
A method declared as public function getName() can be called from outside the class. This is the surface the class exposes.
Using public properties and methods
A public property can be read and written directly. For example, in a User class with public string $name, after $user = new User() you can assign $user->name = "Alex" and read with echo $user->name.
Likewise, a public function greet() can be called as $user->greet() from outside the class.
But beware: since public properties can be changed directly, data that needs internal consistency should use stricter visibility. We'll see this in the next lessons.
Exercise User class with public properties
Define a User class with two public properties: $name and $email (both string). Add a __construct(string $name, string $email) that assigns them. Then create $user = new User("Alex", "alex@example.com") and print echo $user->name . "\n".
Show example solution
Declare public properties, assign them in __construct via $this->name = $name, reach them with $user->name.
Example solution:
<?php
// Define a User class and test external access
class User {
public string $name;
public string $email;
public function __construct(string $name, string $email) {
$this->name = $name;
$this->email = $email;
}
}
$user = new User("Alex", "alex@example.com");
echo $user->name . "\n";
Test yourself
-
When is public access appropriate?
- For properties only subclasses should reach
- For properties that need direct outside access
- For properties only the declaring class should reach
- For properties no one should ever reach
Show answer
For properties that need direct outside access — Correct. public fits properties and methods that need direct outside access.
-
Declare a public property
class User { ____ }Show answer
class User { public $name; } -
Match the public expressions
- public property
- Accessible everywhere
- public method
- Callable from outside
- $user->name
- External access example
- public string $name
- Property declaration