What is the proper way to declare variables in php? - 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?

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

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

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
}

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

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.

Related

Dynamic content, shows a 1 on each request

With my function what I have written I try thereby 2 things.
The links should be called like this http://localhost/?login=Bla, Now it is like this http://localhost/login,php?login "Bla
Next I would have asked, in my function a 1 is given after each call. I just can't figure out where this comes from, I've been sitting on this problem for a long time.
Output with the 1
This is the code with which I can call the pages
function Seite($pagename, $lay){
function Seite($pagename, $lay){
$path = "$lay/$pagename.php";
if (file_exists($path)) {
openSeite($path);
}
}
function openSeite($pageurl){
$fc = require($pageurl);
echo $fc;
}
function echopage($slug, $fade){
// $slug = ?SLUG=Seite
// $fade = Ordner des Layout
$page = isset($_GET["$slug"]) ? $_GET["$slug"] : "error";
$contente = seite($page, "$fade");
echo $contente;
}
I call the content on the index.php with
<? echopage("login", "admin/layout"); ?>
isset($_GET["$slug"]) returns a 1 because it is set (true), write a traditional conditional with the echo inside the if statement.
*Better Yet assign your output to a variable and concatenate the values accordingly.
$output = NULL;
if(isset($_GET["$slug"]){
$contente = seite($page, "$fade");
$output .= $contente;
}else{
//handle error
}
HTML:
<?=$output?><!--Output your displayed text held in the variable-->
ISSUE:
$page = isset($_GET["$slug"]) ? $_GET["$slug"] : "error";
You are essentially returning the set value, which is 1 also true.
From php manual for value: Returns TRUE if var exists and has any value other than NULL. FALSE otherwise.
You can test this by simply writing out a line of code echo isset($var); and checking the test php page. Then try defining a variable and doing the same thing. $var = "this is set"; then echo isset($var);, you will get a 1.

making dynamic defined constants php

look at this syntax of variable name modifying:
${'a' . 'b'} = 'hello there';
echo $ab;
this returns "hello there"
But i want do declare defined variables dynamical.
$error_code = $_GET[error_code]; //for example: 404
define(E404, 'Not found');
echo E{$error_code};
It return error, i want to generate E404 dynamical on php codes and get its value.
I have no idea what the syntax or the technique I'm looking for is here, which makes it hard to research.
You need to call constant() to retrieve the value of a constant from a string. Your example should look like:
$error_code = 404;
define('E404', 'Not found');
echo constant("E{$error_code}");
and it will display Not found.
<?php
$ErrorCode = $_GET['error_code']; // Where error_code = 404
$Errors = array(); // here we are creating a new array.
$Errors[$ErrorCode] = "Whatever"; // here we are setting a key of the new array, with the keys name being equal to the $ErrorCode Variable
print_r($Errors); // Would return Array( [404] => Whatever);
echo $Errors["404"]; // Would return Whatever
?>
Well Php has a feature called variable variables. See this link: http://php.net/manual/en/language.variables.variable.php. It allows a variable name to be assigned to a variable.

Using a variable variable in an object property in PHP

I've set a few variables:
$field = "XYZ";
$block_hi = $field."_hi";
$block_lo = $field."_lo";
Then I have an object with properties that have the name of my above variables:
$obj->XYZ_hi['val'] = "value1";
$obj->XYZ_lo['val'] = "value2";
I thought I could use PHP's variable variables to reference the properties:
print( $obj->${$block_hi}['val'] );
print( $obj->${$block_lo}['val'] );
I expected to get:
value1
value2
However those lines throw errors in apache's error_log:
PHP Fatal error: Cannot access empty property in script.php
This would work, you had the double $$ which wasn't needed in this instance.
$field = "XYZ";
$block_hi = $field."_hi";
$block_lo = $field."_lo";
print($node->{$block_hi}['val']);
print($node->{$block_lo}['val']);

prepend $ to a string to make it a variable

How do I prepend the $ sign to a string to make it a variable?
Eg:
$consumer = array()
$industrial = array()//These 2 are in a separate include file.
$var = $_GET['val'] // value here is 'consumer'
function ('$'.$var,$bar) //I'm trying to make consumer -> $consumer
Not the best way to reach that value, but PHP supports: $$var :)
$$var
will be what you want. The second $ means that the value of the variable should be used as the name of the variable.
http://php.net/manual/en/language.variables.variable.php has more details.
$consumer = array()
$industrial = array()//These 2 are in a separate include file.
$var = $_GET['val'] // value here is 'consumer'
function ($$var,$bar) //I'm trying to make consumer -> $consumer
Don't forget to check that the value of $_GET['val'] is a value you (the programmer) expect and nothing else.
Why not just:
if ($_GET['val'] == 'customer') {
function($bar);
}
Just do the following:
$var = 'myString';
${$var} = 'output';
echo $myString;
Ok, here's that whitelisting you should definitely include.
$whitelist = array('customer', 'consumer');
$fallback = $whitelist[0];
$var = in_array($whitelist, $_GET['val'] ? $_GET['val'] : $fallback;

php lessons/practice. need help understanding if/else

ok so im here trying to practice some php (im a super beginner) and so long story short,
i put form elements in one page, passed it to the process php.
Im just messing aound trying to see what ive learned so far. i dont get any errors, just dont understand why it doesnt work.
<?php
$yourname = htmlspecialchars($_POST['name']);
$compname = htmlspecialchars($_POST['compName']);
$response = array("please enter correct information","hmm" . "$yourname");
function nametest() {
if (!isset($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
?>
<?php nametest(); ?>
what im trying to do is, that if the name isnt set, to make a variable equal to a value inside response.
Try
function nametest() {
if (!isset($yourname)){
$yourname = $response[0];
} else {
$yourname = $response[1];
}
return $yourname;
}
print nametest();
The function needs to return a value to be printed. I also noticed you have two ;; behind line 5.
Because you are assigning $yourname and $compname in the first two lines:
$yourname = htmlspecialchars($_POST['name']);
$compname = htmlspecialchars($_POST['compName']);
UPDATE You can check if these are set in POST, and therefore not need to check them later:
$yourname = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : "oops, no value";
$compname = isset($_POST['compName']) ? htmlspecialchars($_POST['compName']) : "oops, no value";
They will always be set, even if NULL or empty. So, your later calls to isset() will always be true.
Instead, you may check if they are empty with the empty() function:
UPDATE Not necessary according to corrections in comments. Your isset() should work.
// Check with empty()
// but still won't work properly. keep reading below...
function nametest() {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
However, there is another problem here of variable scope. The variables are not available inside the function unless you either pass them in as parameters or use the global keyword:
// $yourname is passed as a function argument.
function nametest($yourname, $response) {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
Getting there... Now your function assigns $yourname, but it doesn't return or print any value. Add a return statement, and then you can echo out the result:
function nametest($yourname, $response) {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
// Add a return statement
return $yourname;
}
// Now call the function, echo'ing its return value
echo nametest($yourname, $response);
Variable Scope is the biggest mistake here, your function can not 'see' the variables that you created outside of it, do this:
<?php
.
.
.
function nametest($yourname, $response) { // This creates two new variables that
// are visible only by this function
if (!isset($yourname)){
$yourname = $response[0];
} else {
$yourname = $response[1]; // Get rid of the extra semicolon
}
return $yourname; // This $yourname is only visible by this function so you
// need to send it's value back to the calling code
}
?>
<?php nametest($yourname, $response); ?> // This sends the values of the
// variables that you created at the
// top of this script

Categories