Classes and Objects in PHP with syntax and examples
Classes are templates for creating objects, encapsulating data and behavior. Objects are instances of classes, representing real-world entities.
Class Syntax:
class ClassName {
// properties
public $property1;
protected $property2;
private $property3;
// constructor
public function __construct($arg1, $arg2) {
$this->property1 = $arg1;
$this->property2 = $arg2;
}
// methods
public function method1() {
// code
}
protected function method2() {
// code
}
private function method3() {
// code
}
}
Constructor Syntax:
public function __construct($arg1, $arg2) {
// initialization code
}
Example:
class User {
public $name;
protected $email;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
public function sayHello() {
echo "Hello, my name is $this->name!";
}
}
$user = new User("Saifosys", "saifosys@gmail.com");
$user->sayHello(); // outputs "Hello, my name is Saifosys!"
Object Properties:
- public: Accessible from anywhere
- protected: Accessible within the class and its descendants
- private: Accessible only within the class
Object Methods:
- public: Callable from anywhere
- protected: Callable within the class and its descendants
- private: Callable only within the class
Constructor Purpose:
- Initializes object properties
- Sets default values
- Performs setup tasks
Best Practices:
1. Use meaningful class and property names
2. Encapsulate data and behavior
3. Use constructors for initialization
4. Validate and sanitize input data
5. Test class functionality thoroughly
By understanding classes and objects in PHP, you can create structured, reusable code and represent real-world entities in your applications.