-
-
Save JettIsOnTheNet/bb2dce44a5dc31573ae4ceb18276ea08 to your computer and use it in GitHub Desktop.
Syntax example scan sheet for PHP.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// php open tag | |
// class definition | |
class Person | |
{ | |
public $firstName; | |
public $lastName; | |
public $age; | |
public function __construct($firstName, $lastName, $age) | |
{ | |
$this->firstName = $firstName; | |
$this->lastName = $lastName; | |
$this->age = $age; | |
} | |
} | |
// functions | |
function greet($name) | |
{ | |
return "Hello " . $name . "!"; | |
} | |
// creating an instance of Person | |
$person1 = new Person("John", "Doe", 30); | |
// accessing fields of the class | |
echo "First Name: " . $person1->firstName . "\n"; | |
echo "Last Name: " . $person1->lastName . "\n"; | |
echo "Age: " . $person1->age . "\n"; | |
// instance with field names | |
$person2 = new Person(firstName: "Alice", lastName: "Smith", age: 28); | |
$integerVar = 10; | |
$stringVar = "Hello, PHP!"; | |
// functions | |
echo greet("World") . "\n"; | |
// loops | |
// for loop | |
for ($i = 0; $i < 5; $i++) { | |
echo "For loop iteration: " . $i . "\n"; | |
} | |
// conditional statements | |
if ($integerVar > 5) { | |
echo "Integer is greater than 5\n"; | |
} elseif ($integerVar == 5) { | |
echo "Integer is 5\n"; | |
} else { | |
echo "Integer is less than 5\n"; | |
} | |
// conditional statements using switch | |
switch (true) { | |
case $integerVar > 5: | |
echo "Integer is greater than 5\n"; | |
break; | |
case $integerVar == 5: | |
echo "Integer is 5\n"; | |
break; | |
default: | |
echo "Integer is less than 5\n"; | |
} | |
// data structures | |
$myArray = [1, 2, 3, 4, 5]; | |
$myMap = ["a" => 1, "b" => 2]; | |
// error handling | |
$fileHandle = @fopen("nonexistent_file.txt", "r"); | |
if (!$fileHandle) { | |
echo "Error opening file: " . error_get_last()["message"] . "\n"; | |
} | |
// writing to a file | |
$content = "Writing to a file in PHP!"; | |
file_put_contents("example.txt", $content); | |
// reading from a file | |
$data = file_get_contents("example.txt"); | |
echo "File content: " . $data . "\n"; | |
// close tag not required, but recommended | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment