PHP Person Class Example: Set Name, Get Name
This Snippet is coded by a user inOnline php Compiler. You can see and run this code too.
زبان: PHP
This code demonstrates a simple Person class in PHP, highlighting the use of private properties, a setter (setName) and a getter (getName). The class encapsulates the name property and only allows controlled access via public methods. Type hinting (string) ensures that the name is a string. The example then creates an object, sets the name to “Mostafa”, and prints the result. This is a fundamental pattern in object-oriented programming (OOP) for data encapsulation and validation.
- Private property for encapsulation
- Public methods for access
- Typed parameter for safety
- Object instantiation and method calls