PHP Methods
In PHP, methods are functions that belong to a class. When you create an object-oriented program, you define methods inside a class to perform specific actions on objects.
What is a Method in PHP?
✔ A method is just a function inside a class.
✔ It is used to define behaviors for objects.
✔ Methods can access and modify object properties.
✔ They can have parameters and return values like regular functions.
Defining a Method in a Class
✔ Use the public
, private
, or protected
keyword to define a method.
class Car {
public $brand;
// Method to set the brand
public function setBrand($name) {
$this->brand = $name;
}
// Method to get the brand
public function getBrand() {
return $this->brand;
}
}
// Creating an object of the class
$myCar = new Car();
$myCar->setBrand("Toyota");
echo $myCar->getBrand(); // Output: Toyota
✔ setBrand()
sets the car brand.
✔ getBrand()
retrieves the car brand.
Access Modifiers in Methods
✔ public
– Can be accessed from anywhere.
✔ private
– Can only be accessed inside the class.
✔ protected
– Can be accessed within the class and its child classes.
class User {
private function greet() {
return "Hello!";
}
public function showGreeting() {
return $this->greet(); // Works because it's inside the class
}
}
$user = new User();
echo $user->showGreeting(); // Output: Hello
// echo $user->greet(); // ❌ ERROR: Cannot access private method
✔ Private methods can only be called inside the class.
Static Methods
✔ A static method can be called without creating an object.
✔ Use the static
keyword.
class Math {
public static function add($a, $b) {
return $a + $b;
}
}
// Calling the method without creating an object
echo Math::add(5, 10); // Output: 15
✔ Math::add(5, 10)
calls the method directly.
Constructor Method
✔ A constructor is a special method that runs automatically when an object is created.
✔ Use the __construct()
method.
class Person {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function greet() {
return "Hello, " . $this->name;
}
}
$person = new Person("Alice");
echo $person->greet(); // Output: Hello, Alice
✔ The constructor assigns a value to $name
automatically when creating an object.
Conclusion
✔ Methods are functions inside classes that define object behavior.
✔ Access modifiers (public
, private
, protected
) control method visibility.
✔ Static methods can be called without creating an object.
✔ Constructors run automatically when an object is created.