Using Functions, Classes, Objects, and Forms in
PHP
Functions in PHP
Functions in PHP help in reusability and modularity.
1. Function Definition & Invocation
<?php
function greet($name) {
return "Hello, $name!";
}
echo greet("Anmol"); // Output: Hello, Anmol!
?>
2. Formal vs Actual Parameters
Formal Parameters: Parameters in function
definition.
Actual Parameters: Values passed when calling
the function.
<?php
function add($a, $b) { // $a and $b are formal
parameters
return $a + $b;
}
echo add(5, 10); // 5 and 10 are actual
parameters
?>
3. Function and Variable Scope
Global Scope: Declared outside functions.
Local Scope: Declared inside functions.
Static Variables: Retains value across function
calls.
<?php
$globalVar = 10; // Global Scope
function testScope() {
global $globalVar; // Access global
variable
echo "Global Variable: $globalVar\n";
static $counter = 0; // Static Variable
$counter++;
echo "Counter: $counter\n";
}
testScope();
testScope();
?>
4. Recursion in PHP
A function calling itself.
<?php
function factorial($n) {
if ($n <= 1) return 1;
return $n * factorial($n - 1);
}
echo factorial(5); // Output: 120
?>
5. Library Functions (Built-in)
Examples: strlen(), date(), strtolower(), rand(),
etc.
<?php
echo "Random Number: " . rand(1, 100) . "\n";
echo "Current Date: " . date("Y-m-d");
?>
Date and Time Functions
PHP provides built-in functions for handling date and
time.
<?php
echo "Current Date: " . date("Y-m-d H:i:s") .
"\n";
echo "Day of the Week: " . date("l") . "\n";
?>
Strings in PHP
1. Creating and Declaring Strings
<?php
$str1 = "Hello, PHP!";
$str2 = 'Single-quoted String';
echo $str1 . "\n" . $str2;
?>
2. String Functions
<?php
echo strlen("Hello"); // Output: 5
echo strtoupper("hello"); // Output: HELLO
echo str_replace("World", "Anmol", "Hello
World"); // Output: Hello Anmol
?>
Classes & Objects in PHP
PHP is an Object-Oriented language.
1. Creating a Class & Object
<?php
class Car {
public $brand;
function setBrand($name) {
$this->brand = $name;
}
function getBrand() {
return $this->brand;
}
}
$car1 = new Car();
$car1->setBrand("Toyota");
echo $car1->getBrand(); // Output: Toyota
?>
Forms in PHP
Forms allow user interaction.
<!DOCTYPE html>
<html>
<body>
<form method="post">
Name: <input type="text" name="username">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["username"];
echo "Hello, " . htmlspecialchars($name);
}
?>
</body>
</html>
Do you need any specific examples or explanations? 🚀