Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to declare variables in php?

Tags:

php

I was using variables in my php file without declaring them. It was working perfect in old version of localhost (i.e vertrigoServ 2.22).

But when I moved to latest version of localhost (i.e xampp 3.2.1), I encountered variables declaration warnings and errors something like this:

Notice: Undefined variable: att_troops_qty in D:\Installed Programs\htdocs\dashboard\WarLord\PHP_Code\MyAjax.php on line 1247

So I declared all the variables at the top of php file like this:

$page = "";
$att_troops_qty = "";
$def_troops_qty = "";
$ca_level = "";
$b_level = "";
$pre_buildings = "";
$created_pre_b = "";
$building_id = "";
$building_loc = "";
$ca_1_b_loc = "";
$ca_1_b_level = "";
$ca_2_b_loc = "";
$ca_2_b_level = "";

It solved the problem But I have confusion that this is not the proper way to declare variables.

Is there some more better way for variables declaration?

like image 821
Rashid Avatar asked Nov 21 '25 12:11

Rashid


2 Answers

How you are declaring is perfectly alright and proper way.

$test = "";

or

$test = null;

these both are proper ways for declaring empty variables. for more info please visit http://php.net/manual/en/language.types.null.php

like image 80
Renuka CE Avatar answered Nov 24 '25 02:11

Renuka CE


You need to declare variables before echoing them out. An example is here:

<?php
    $var = "test";
    echo $var; // it will echo out test
?>

And trying to echo out a variable this way will generate an error:

<?php
    echo $var; // it will generate error
    $var = "test";
?>

In addition, you can declare variables in another file and can include that file to echo out the variable somewhere. Remember to include the file first and then call it.

Example vars.php:

<?php
    // define vars
    $var1 = "Test 1";
    $var2 = "Test 2";
?>

Now in another file, include vars.php first and then call the variable:

<?php
    require_once"vars.php";
    echo $var1;
?>
like image 42
Rehmat Avatar answered Nov 24 '25 01:11

Rehmat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!