What is the proper way to declare variables in php?

那年仲夏 提交于 2020-01-30 06:31:48

问题


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?


回答1:


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




回答2:


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;
?>



回答3:


The best way to check whether the variable is declare or not, is to use the isset() function, which checks whether the variable is set or not like:

<?php
    if(isset($a)){
       // execute when $a is set ( already declare ) or have some value
    }
    else {
      // execute when $a not set
   }
?>



回答4:


You cannot use undeclared variables but you can declare them on the go.

Inside functions you can do something like that:

function abc() {
    return $newVar or null; // without variable declaration
}

If $newVar is not declared before function will return null;

Or better way:

function abc($newVar = null) {
    return $newVar; // with variable declaration
}



回答5:


You can declare variables in php as

<?php
   $test = "xyz" //for String datatype
   $test1 = 10 //for integer datatype
?>

Name of a variable declared must be alphanumeric and you don't need to specify the type.



来源:https://stackoverflow.com/questions/34470470/what-is-the-proper-way-to-declare-variables-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!