PHP Keywords

By Shahnail Khan Last updated : December 7, 2023

Like any programming language, PHP has its set of reserved words known as keywords. In this tutorial, we'll explore PHP keywords, including their definition, and syntax.

PHP Keywords

Keywords have specific meanings in the language and cannot be used for naming variables, functions, or classes.

PHP Keywords List

Keyword Description Syntax
abstract Used to declare an abstract class or method abstract class Shape { abstract function draw(); }
and Logical AND operator if ($age >= 18 and $hasID) { ... }
array Used to declare an array $fruits = array("apple", "banana", "orange");
as Used to alias a class or function use DateTime as MyDate;
break Exits a loop or switch statement for ($i = 0; $i < 10; $i++) { if ($i === 5) { break; } }
callable Represents a callable entity (function or method) $callback = function($a, $b) { return $a + $b; };
case Used in switch statements switch ($day) { case "Monday": ...; case "Tuesday": ...; }
catch Exception handling block try { ... } catch (Exception $e) { ... }
class Used to declare a class class User { public $name; public function __construct($name) { $this->name = $name; } }
clone Creates a copy of an object $user2 = clone $user1;
const Used to define a constant const PI = 3.14159265359;
continue Skips the current iteration of a loop for ($i = 0; $i < 10; $i++) { if ($i === 5) { continue; } ... }
declare Declares variables with specific types declare(strict_types=1);
default Used in switch statements switch ($day) { case "Monday": ...; default: ...; }
die Prints a message and exits the script die("Error!");
do Used with while loop to execute code at least once do { ... } while ($condition);
echo Outputs a string echo "Hello, World!";
else Used with if statements if ($age >= 18) { ... } else { ... }
elseif Used with if statements as a shortcut for "else if" if ($age >= 21) { ... } elseif ($age >= 18) { ... } else { ... }
empty Checks if a variable is empty if (empty($name)) { ... }
enddeclare Used to close a declare block enddeclare();
endfor Ends a for loop for ($i = 0; $i < 10; $i++) { ... } endfor;
endforeach Ends a foreach loop foreach ($fruits as $fruit) { ... } endforeach;
endif Ends an if statement if ($age >= 18) { ... } endif;
endswitch Ends a switch statement switch ($day) { ... } endswitch;
endwhile Ends a while loop while ($condition) { ... } endwhile;
eval Evaluates a string as code eval('$result = 1 + 2;');
exit Prints a message and exits the script exit("Error!");
extends Used to inherit properties and methods from another class class User extends Person { ... }
final Prevents a class from being inherited final class Logger { ... }
finally Always executes after a try/catch block, regardless of whether an exception was thrown try { ... } catch (Exception $e) { ... } finally { ... }
for Looping structure for ($i = 0; $i < 10; $i++) { ... }
foreach Looping structure for traversing arrays foreach ($fruits as $fruit) { ... }
function Used to define a function function sum($a, $b) { return $a + $b; }
global Used to declare variables accessible within the current scope global $name;
goto Jump to a specific label within the script goto myLabel;
if Conditional statement if ($age >= 18) { ... }
implements Used in a class to implement an interface class MyClass implements MyInterface { ... }
include Includes and evaluates a specified file include "filename.php";
include_once Includes and evaluates a file only once include_once "filename.php";
instanceof Checks if an object is an instance of a class if ($obj instanceof MyClass) { ... }
insteadof Used in trait to specify a precedence of a certain trait over another use Trait1, Trait2 { Trait1::method insteadof Trait2; }
interface Declares an interface interface MyInterface { ... }
isset Checks if a variable is set if (isset($variable)) { ... }
list Assigns variables as if they were an array list($a, $b) = [1, 2];
namespace Declares a namespace namespace MyNamespace;
new Creates a new object $object = new ClassName();
or Logical OR operator if ($condition1 or $condition2) { ... }
print Outputs a string print "Hello, World!";
private Specifies that a method or property can only be accessed within the class private $name;
protected Specifies that a method or property can only be accessed within the class and its subclasses protected $name;
public Specifies that a method or property can be accessed from outside the class public $name;
require Requires and evaluates a specified file require "filename.php";
require_once Requires and evaluates a file only once require_once "filename.php";
return Exits a function and returns a value function add($a, $b) { return $a + $b; }
static Declares a static method or property static $counter = 0;
switch Selects one of many blocks to be executed switch ($day) { case "Monday": ...; break; }
throw Throws an exception throw new Exception("Error message");
trait Introduces a trait into a class class MyClass { use MyTrait; }
try Implements exception handling try { ... } catch (Exception $e) { ... }
unset Unsets a variable unset($variable);
use Imports a namespace or trait use MyNamespace\MyClass;
var Declares a variable var $name;
while Creates a while loop while ($condition) { ... }

PHP Keywords Examples

Explore these examples to understand about the keywords in PHP scripts.

To understand both of the examples, you should have the knowledge of the following PHP topics:

Example 1

Create a PHP function called divideNumbers that takes two parameters and returns the result of dividing them. Handle division by zero using a try-catch block and throw a custom exception. (Learn: Exception Handling in PHP)

<?php

function divideNumbers($numerator, $denominator)
{
    try {
        if ($denominator === 0) {
            throw new Exception("Cannot divide by zero");
        }

        return $numerator / $denominator;
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    }
}

$result = divideNumbers(10, 0);

?>

The output of the above example is:

Error: Cannot divide by zero

In this example, we have a function called "divideNumbers" that divides two numbers. The tricky part is, if the second number (denominator) is zero, it can cause an error. So, we use the keywords try, catch, and throw to handle this situation. When the denominator is zero, the program doesn't stop executing; instead, it throws a special message saying "Cannot divide by zero," and the program continues running without any major problems.

Example 2

You are asked to implement a simple arithmetic calculator in PHP. Write a function "calculate" that takes two numbers and an arithmetic operator as parameters and returns the result of the operation.

  • The function should handle addition (+), subtraction (-), multiplication (*), and division (/) operations.
  • For division, return null if the second number is zero.
  • If the operator is not one of the valid arithmetic operators, return null.

Solution

Read the problem carefully. Once you read, think of the easiest approach. Since we have to perform three tasks, we can use the switch statement.

<?php
function calculate($num1, $num2, $operator)
{
    switch ($operator) {
        case "+":
            return $num1 + $num2;
        case "-":
            return $num1 - $num2;
        case "*":
            return $num1 * $num2;
        case "/":
            // Check for division by zero
            return $num2 != 0 ? $num1 / $num2 : null;
        default:
            return null; // Invalid operator
    }
}

// Test the function with the provided examples
$result1 = calculate(5, 3, "+");
$result2 = calculate(10, 4, "-");
$result3 = calculate(6, 2, "*");
$result4 = calculate(8, 2, "/");
$result5 = calculate(8, 2, "%");

echo $result1 . "<br>";
echo $result2 . "<br>";
echo $result3 . "<br>";
echo $result4 . "<br>";
var_dump($result5);

?>

The output of the above example is:

8
6
12
4
NULL

This solution uses a switch statement to perform the appropriate arithmetic operation based on the provided operator. The function returns the result of the operation or null for invalid operators or division by zero.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.