PHP has a set of keywords that have special meanings, and these are reserved words that are used by the language for specific tasks. Let's delve into these PHP keywords with examples:
$age = 18;
if ($age < 18) {
echo "You are a minor.";
} elseif ($age == 18) {
echo "You just became an adult!";
} else {
echo "You are an adult.";
}
$day = 'Monday';
switch ($day) {
case 'Monday':
echo "It's the start of the week.";
break;
case 'Friday':
echo "Weekend is near!";
break;
default:
echo "It's a normal day.";
break;
}
for ($i = 0; $i < 5; $i++) {
echo $i;
}
$arr = [1, 2, 3];
foreach ($arr as $value) {
echo $value;
}
$i = 0;
while ($i < 5) {
echo $i;
$i++;
}
$i = 0;
do {
echo $i;
$i++;
} while ($i < 5);
2. Function and Class Keywords:
function greet() {
return "Hello, World!";
}
class Animal {
public $name;
function __construct($name) {
$this->name = $name;
}
protected function getDetails() {
return "This is an animal named " . $this->name;
}
}
class Dog extends Animal {
const TYPE = "Mammal";
public function displayDetails() {
return $this->getDetails();
}
}
$dog = new Dog("Buddy");
echo Dog::TYPE; // Outputs: Mammal
echo $dog->displayDetails(); // Outputs: This is an animal named Buddy
3. Other Keywords:
Used to display output.
echo "Hello!";
print "World!";
Used for including other PHP files.
include 'file.php';
require 'file.php';
include_once 'file.php'; // Ensures the file is included only once
require_once 'file.php'; // Ensures the file is required only once
Used to access global variables from within a function.
$x = 10;
function test() {
global $x;
echo $x;
}
test(); // Outputs: 10
$var = "";
if (isset($var)) { // Checks if variable is set
echo "Variable is set.";
}
if (empty($var)) { // Checks if variable is empty
echo "Variable is empty.";
}
unset($var); // Destroys the variable
`die`, `exit`:
Used to halt script execution.
if (!file_exists('file.php')) {
die('File not found.');
}
$arr = array(1, 2, 3);
list($a, $b, $c) = $arr;
echo $a; // Outputs: 1
For exception handling.
try {
throw new Exception("An error occurred!");
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "This part is always executed.";
}
This is a broad overview of PHP keywords with basic examples. However, it's essential to dive deeper into each concept and practice them to understand them fully.
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here