Reputation: 1057
In the lower versions of php I used to use the following code to show object property in the page :
<input type=text value='<?php echo $obj->title ;?>'>
In the edit mode $obj was an object fetched from database and user could see the already existed value, and for insert mode there was no $obj because there was no $_GET["obj_id"] and $obj wasn't defined so the input field was shown empty ,
In the new versions php stops the insert pages because $obj isn't defined or has no property named title , So I should use something like this :
<input type=text value='<?php echo isset($obj)?$obj->title:"" ;?>'>
Now what I want to do is to make this some shorten, I created a function like the following but it doesn't seem to work and keeps showing the error,
function showprop($obj,$prop)
{
if( isset($obj) )
echo $obj->{$prop};
else
echo "";
}
<input type=text value='<?php showprop($obj,"title");?>'>
Any suggestion to make this work without getting notice? Thanks in advance
Upvotes: 0
Views: 203
Reputation: 2127
It won't work because the $obj
is not defined. But you can pass the variable of the name to the function and check whether the global variable is defined in that function - but this is ugly:
function showprop($obj,$prop)
{
if( isset($_GLOBALS[$obj]) )
echo $_GLOBALS[$obj]->{$prop};
else
echo "";
}
<input type=text value='<?php showprop('obj',"title");?>'>
Upvotes: 1
Reputation: 522135
A function is not going to work, since PHP will try to resolve $obj
before passing its value into the function, so you're left with the same problem.
Use the null coalescing operator instead (available from PHP 7):
<?= $obj->title ?? '' ?>
Upvotes: 4