☜
☞
Functions
Function
In PHP, a function is a block of code that can be called by name. Functions allow you to reuse code and modularize your scripts by breaking them up into smaller, self-contained units of functionality.
Here is an example of a simple function in PHP:
function sayHello($name) {
echo "Hello, $name!";
}
To call a function, you simply use its name followed by parentheses and any necessary arguments:
sayHello("John"); // prints "Hello, John!"
Functions can also accept multiple arguments and return a value:
function add($x, $y) {
return $x + $y;
}
echo add(2, 3); // prints 5
Functions can also be defined inside classes, in which case they are called methods. Here is an example of a method in a class:
class Person {
public $name;
public function sayHello() {
echo "Hello, my name is $this->name.";
}
}
Functions are a powerful and important feature of PHP, as they allow you to reuse code and modularize your scripts. They also help to make your code more organized and easier to maintain.
☜
☞