Project PHP

mail@pastecode.io avatar
unknown
php
12 days ago
1.9 kB
9
Indexable
Never
<?php
// Example of a function and datatypes of variables
function addNumbers(int $num1, int $num2): int {
    return $num1 + $num2;
}

$num1 = 10; // Declaration of an integer variable $num1
$num2 = 20; // Declaration of an integer variable $num2

$sum = addNumbers($num1, $num2); // Calling addNumbers function with $num1 and $num2 as arguments
echo "Sum: $sum\n"; // Outputting the result of the addition

// Example of print and echo
$name = "John"; // Declaration of a string variable $name
echo "Hello, $name!\n"; // Using echo to output a greeting message
print("Hello, $name!\n"); // Using print to output the same greeting message

// Built-in function for strings (str) and function for integers (int)
$stringLength = strlen("Hello, world!"); // Using strlen function to get the length of a string
$integerValue = intval("42"); // Using intval function to convert a string to an integer

echo "Length of string: $stringLength\n"; // Outputting the length of the string
echo "Integer value: $integerValue\n"; // Outputting the converted integer value

// Example of the difference between define and const
define("PI", 3.14159); // Defining a constant PI using define
const GREETING = "Hello, world!"; // Defining a constant GREETING using const

echo "Value of PI: " . PI . "\n"; // Outputting the value of the constant PI
echo "Greeting: " . GREETING . "\n"; // Outputting the value of the constant GREETING

// Example of variable scope
function testScope() {
    $localVariable = "I'm local!"; // Declaration of a local variable $localVariable
    echo $localVariable . "\n"; // Outputting the value of the local variable
}

testScope(); // Calling the function testScope, which outputs the value of the local variable

// echo $localVariable; // This line would cause an error because $localVariable is not defined in this scope

?>
Leave a Comment