NetizenKing NetizenKing - 1 year ago 116
PHP Question

Accessing PHP 7 Object Properties

I have the following array

$arrdata = array("CTypeID","TypeName","CTYPES","CID","COURSES","CTypeID");

this array is subjected to a function:

The definition of the called function is as follows:

function Generic2DataSideBar($data)
//a generic array for data..
$sdata= array();
//this is the function for generating depended data...
$dat="SELECT ".$data[0].",".$data[1]." FROM ".$data[2];
//Looping through the resultset
foreach ($result as $key) {
//get the number of departments

$da="SELECT ".$data[3]." FROM ".$data[4]." WHERE ".$data[5]."='".$key->$data[0]."'";

$r=array($key->$data[1], $dat);
array_push($sdata, $r);
header("content-type: application/json");
return $sdata;

This function is working well in PHP 5.6.3 but when i upgraded to PHP 7, the line
$da="SELECT ".$data[3]." FROM ".$data[4]." WHERE ".$data[5]."='".$key->$data[0]."'";
brings a problem in that
All values are OK except that part. In PHP 7 can't one have something like
so long "Data" is a valid property name? Thanks

Answer Source

As you can see in the documentation, the interpretation of $key->$data[0] changed from PHP 5 to PHP 7 (the second row of the table).

In order to get the same results as on PHP 5 you can do one of these:

  1. extract $data[0] in a variable and use that variable instead:

    $field = $data[0];
    "... WHERE ".$data[5]."='".$key->$field."'";
  2. use curly braces to group the sub-expressions that need to be evaluated first:

    "... WHERE ".$data[5]."='".$key->{$data[0]}."'";

Both ways are compatible with PHP 5 and doesn't change the behaviour of the code on PHP 5.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download