Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why PHP doesn't throw an error on missing semicolon?

Tags:

php

The code below works perfectly in PHP. Can anyone explain to me how this code works? In the below code, I have declared $caregory_id without a semicolon and any value assignment. Then also this code works perfectly without any error and var_dump($category_id) returns me a null value.

How does PHP execute this code without a semicolon?

<?php
    $category_id= //No semicolon
    var_dump($category_id); //returns NULL
?>
like image 864
Pathik Gandhi Avatar asked Sep 17 '26 09:09

Pathik Gandhi


1 Answers

It works because PHP treats your code like this:

$category_id = var_dump($category_id);

The return value of var_dump() gets assigned to $category_id. Undefined variables in PHP are implicitly set to null, which is what you see in the output of var_dump(). However, you would also get a notice about $category_id not being defined; if you don't see it, you should use this code in your script:

error_reporting(-1);
ini_set('display_errors', 'On');

These settings are also recommended during development as they can catch issues that would otherwise have gone unnoticed on a production machine.

like image 51
Ja͢ck Avatar answered Sep 18 '26 21:09

Ja͢ck