Categories
Beginner

Basic PHP Tutorial (Part 03)

Functions in PHP

  • Always starts with the keyword function.
function func_with_no_parameters(){
    echo "here";
}
func_with_no_parameters(); // prints here
  • Can receive parameters
function func_with_parameters($x, $y){
    echo $x * $y;
}
func_with_parameters(2, 3); // prints 6
  • Can have return statements
function func_with_parameters($x, $y){
    if($x==2){
        return;
    }
    echo $x * $y;
}
func_with_parameters(2, 3); // prints 6?
function func_with_parameters($x, $y){
    return $x * $y;
}
echo func_with_parameters(2, 3); // prints 6

Include Files

  • Sometimes you write your code in separate files.
  • Then you need to include your other files.
include "some_other_file.php"; // includes some_other_file.php
include "some_folder/some_other_file.php"; // includes from sub folder some_folder

// what if the files both include eachother (circular dependency)?
  • Don’t create circular dependency (two files including each other).
  • Use require_once to raise an error if the file is not found.
require_once "some_other_file.php"; // require once some_other_file.php

Multi Line Comments

/**
 * this is the syntax for multi line comments
 * second line.
 * third line.
 */

Errors

  • Errors can occur
  • Read the error to know where it happened
  • Most common errors – Syntax errors.
 //missing semicolon
 $var = 1
 if(true{ //missing parenthesis
 }

Parse error: syntax error, unexpected ‘$var ‘ (T_VARIABLE) in C:\xampp\htdocs\simple\index.php on line 4.

Unidentified Function

<?php
undefined_function(); // calling a function that doesn't exist
?>

Fatal error: Uncaught Error: Call to undefined function undefined_function() in C:\xampp\htdocs\simple\undefined_function.php:3 Stack trace: #0 {main} thrown in C:\xampp\htdocs\simple\undefined_function.php on line 3

<?php

$x = $y; //what is $y?

?>

Notice: Undefined variable: y in C:\xampp\htdocs\simple\undefined_variable.php on line 3

Leave a Reply

Your email address will not be published. Required fields are marked *