Using a variable variable in an object property in PHP - 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']);

Related

Extract xml artist name nusic for string "SONGTITLE" for <div>

Extract xml artist name nusic for string "SONGTITLE" for
<div class="data">
<p class="music">Loading</p>
<p class="singer">Loading</p>
</div>
PHP Warning: Attempt to read property "SONGTITLE" on bool in
Erro part code
$music = htmlspecialchars(addslashes($shoutcast->SONGTITLE));
Userd php 5,6
====
<?php
function Streaming(){
global $radio;
$shoutcast = simplexml_load_file("http://live.radiosoundfm.com.br:8578/stats?sid=1");
$music = htmlspecialchars(addslashes($shoutcast->SONGTITLE));
$singer = ''; $name = $music;
if(strpos($music, '-') !== false && substr_count($music, '-') == 1){
$data = explode('-', $music);
$singer = trim($data[0]) != '' ? trim($data[0]) : '';
$name = trim($data[1]) != '' ? trim($data[1]) : '';
}
$data = array(
'music' => $music,
'name' => $name,
'singer' => $singer
);
return $data;
}
https://github.com/saniellocutor/radiosoundfm.com.br-Site
PHP Warning: Attempt to read property "SONGTITLE" on bool in
The first warning message indicates that the XML load failed and the function returned false. You need to add some error validation at this point.
$shoutcast = simplexml_load_file(...);
if ($shoutcast) {
// read XML
} else {
// log error
}
Also, some servers expect valid user agents. You can use libxml_set_streams_context() provide additional request headers.
PHP Deprecated: addslashes(): Passing null to parameter #1 ($string) of type string is deprecated
So $shoutcast is false and $shoutcast->SONGTITLE is an undefined value. However addslashes() expects a mandatory string parameter in the current PHP versions. You old PHP still allows it, but it warn about the change in newer versions.
The whole line $music = htmlspecialchars(addslashes($shoutcast->SONGTITLE)); looks like pre-emptive escaping. Don't do that. Only escape if you know the target and just before you insert it. Most of the time here are better options (Prepared statements for the database, DOM for HTML outputs, ...).
Reading a string value from SimpleXMLElement:
The 'SimpleXMLElement' instance: $shoutcast->SONGTITLE;
Fallback for missing node: $shoutcast->SONGTITLE ?? '';
Cast to string: (string)($shoutcast->SONGTITLE ?? '');
Assign to variable: $music = (string)($shoutcast->SONGTITLE ?? '');

Member variable does not accept array with elements

After updating WordPress to 6.0.2, I get the "white screen of death" - just stating that
there is a critical error
with no further explanation.
After some debugging I located the line, that produces the error:
/wp-content/plugins/jet-theme-core/includes/locations.php line 53
It's a function of the class Jet_Theme_Core_Locations that assigns an array to $this->_locations[ $id ]
With these declarations
private $_locations = array();
public $test = array();
private $_test = array();
I tested some statements and found out that
$this->_locations = true; // works
$this->_locations = "test"; // works
$this->_locations = array(); // works
$this->_locations = array("test"); // produces a critical error
$this->_locations = array("test" => "test"); // produces a critical error
$this->_locations[] = "test"; // produces a critical error
$this->_locations["test"] = "test"; // produces a critical error
$test = array("test" => "test"); // works
$this->test = array(); // works
$this->test = array("test"); // works
$this->_test = array(); // works
$this->_test = array("test"); // works
I must be missing something. Probably something really obvious. But I can't figure out, what it is.
[Edit:]
The PHP log file says:
PHP Fatal error: Uncaught Error: Class 'Elementor\\Post_CSS_File' not found in /wp-content/plugins/jet-theme-core/includes/locations.php:106
The function enqueue_styles() loops over $this->_locations and calls Elementor\Post_CSS_File but doesn't find it. If $this->_locations is empty or not an array at all, it doesn't touch Elementor\Post_CSS_File and the error doesn't occur.
As suggested here, I replaced
$css_file = new Elementor\Post_CSS_File( $template_id );
with
$css_file = new Elementor\Core\Files\CSS\Post( $template_id );
Now everything works fine.

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

PHP - str_replace returns original string

I'm building a simple JS terminal shell emulator which posts its commands via AJAX to PHP.
Please leave security aside, this is only for learning and demo purposes.
Now my problem is, str_replace() won't work as expected, in fact, it returns the unchanged input string. It should work like this:
The name of this host is $hostname --> Yes, this string contains a variable --> Replace $hostname with testserver --> return The name of this host is testserver
What am I doing wrong?
This is my respond script for echo and export:
<?
// get environment variables from JSON
$vars = json_decode(file_get_contents('environment.json'), true);
// get request params
$method = $_SERVER['REQUEST_METHOD'];
$action = $_POST['action'];
$data = $_POST['data'];
switch ($action) {
case 'echo':
$cmd = $data;
// if the string in question contains a variable, eg. "the time is $time"
if (strpos($cmd,'$')) {
$output = '';
// for each environment variable as variable => value
foreach ($vars as $var => $val) {
// replace every variable in the string with its value in the command
$output = str_replace($var,$val,$cmd);
}
echo $output;
} else {
// if it does not contain a variable, answer back the query string
// ("echo " gets stripped off in JS)
echo $cmd;
}
break;
case 'export':
// separate a variable declaration by delimiter "="
$cmd = explode('=',$data);
// add a $-sign to the first word which will be our new variable
$var = '$' . array_shift($cmd);
// grab our variable value from the array
$val = array_shift($cmd);
// now append everything to the $vars-array and save it to the JSON-file
$vars[$var] = $val;
file_put_contents("environment.json",json_encode($vars));
break;
}
Better using :
if (strpos($cmd,'$') !== false) {
Then, every single replace will take the "first" data as its input data. You should proceed like this :
$output = $cmd;
// for each environment variable as variable => value
foreach ($vars as $var => $val) {
// replace every variable in the string with its value in the command
$output = str_replace($var, $val, $output);
}

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;

Categories