Undefined Index in __isset - php

I am getting an error in my actual code inside __isset, but when I went to a 'run php online website' it works. So I am not sure why it does not work in my code.
<?
class Test {
private $args;
public function __construct($args = array()) {
$this->args = $args;
}
public function __isset($name) {
return $this->args[$name]; //undefined index on my server (is fine on php site)
}
function prnt() {
// echo isset($this->i) ? "set" : "notset"; --> works, both print 'set'
echo isset($this->h) ? "set" : "notset";
}
}
?>
I then execute this:
$test = new Test(array('i' => '1234'));
$test->prnt();
//result on php website: notset
//result on my website: Undefined index at the line shown above.
Possibly helpful information:
My server is running php 5.1.
The isset($this->var) is happening in an include file in my actual code.
As long as the variable exists (like i above) it obviously works.

Your error reporting settings in each environment are different. One environment is allowing errors of E_NOTICE level through while another is blocking them.
You should do something like this:
return array_key_exists($name, $this->args);

You're trying to return the value of a non existent key, instead return the result of testing for the key using array_key_exists
public function __isset($name) {
return array_key_exists($name, $this->args);
}

Related

How to write that in PHP 7.2?

I have this piece of code:
private function _resolveCustomEntries($fields)
{
foreach ($fields as &$value) {
if (array_key_exists('custom', $value)) {
if (method_exists($this, $value['custom'])) {
$value['custom'] = $this->$value['custom'](); //variableInterpolation
}
}
}
return $fields;
}
I ran a PHP 7.2 compatibility check and it complained here with the "variableInterpolation" on the marked line. When I run this code, the PHP log tells me this:
ERR (3): Notice: Array to string conversion in
/public_html/lib/KiTT/Payment/Widget.php on line 217
Thats the same line where the "variableInterpolation" check failed. So how would I rewrite this code so it works in PHP 7.2?
Thanks!
Solution:
$value['custom'] = $this->$value['custom']();
has to look like this:
$value['custom'] = $this->{$value['custom']}();
It's a matter of order variables are evaled.
With
class x {
public function y() {
echo 'ok';
}
}
$x = new x();
$y = array('i' => 'y');
Then
$x->$y['i']();
Fails because PHP first tries to cast the $y variable into a string, and get the matching property of $x (which btw does not exist), then tries to get the index 'i' or that unexisting property, and then tries to run it as a callable.
Hence 3 errors:
Array to string conversion
Undefined property x::$Array
Function name must be a string (nda: the undefined property returns NULL)
Instead, curly brace the variable to set the resolving order:
$x->$y['i']();
Will work. So use $this->{$value['custom']}()
This will throw an array to string conversion in 7.2
class bob{
function foo(){
return 'bar';
}
function getFoo(){
$value['custom'] = 'foo';
$value['custom'] = $this->$value['custom']();
return $value['custom'];
}
}
$bob = new Bob();
var_dump($bob->getFoo());
But it will execute just fine in 5.6.
Then i changed the snippet to this, not calling the method directly casting the array key to function name, but initializing a string (hopefully, there is no type validation in your code) variable with the function name first:
class bob{
function foo(){
return 'bar';
}
function getFoo(){
$value['custom'] = 'foo';
$functionName = $value['custom'];
$value['custom'] = $this->$functionName();
return $value['custom'];
}
}
$bob = new Bob();
var_dump($bob->getFoo());
This will run just fine in php 7.2
You could try rewriting your code using complex (curly) syntax, you can read more about it here.
Your code would look something like this.
$value['custom'] = $this->{$value['custom']}();
Edit: moved the curly braces to correct positions.

Why is the controller executed twice (flashbag, redirectoroute)?

I have two routes /alpha and /beta configured in yml. In alphaAction a notice is placed in the flashbag and a redirecttoroute occurs. In betaAction the notice in the flashbag is read.
Sometimes I get 2 notices when I try /alpha in the browser and sometimes I get one notice.
Can someone explain what is happening, what I'm doing wrong.
public function alphaAction()
{
$this->get('session')->getFlashBag()->add("notice",mt_rand());
return $this->redirectToRoute("beta");
}
public function betaAction()
{
$notices= $this->get('session')->getFlashBag()->get('notice');
return new Response(implode($notices,", "));
}
Using the add method I could reproduce the issues you described. This can be fixed by using the set method and not the add (or setFlash) method.
public function alphaAction()
{
$this->get('session')->getFlashBag()->set("notice",mt_rand());
return $this->redirectToRoute("beta");
}
public function betaAction()
{
$notices= $this->get('session')->getFlashBag()->get('notice');
return new Response(implode($notices,", "));
}

php variable not detected

im having trouble with my php program, it seems that my array variable being declared earlier wasn't detected in a function. Here's my code :
$msg = array(
//Errors List
'Error1' => 'Error 1',
'Error2' => 'Error 2'
);
//Class for outputting Messages
class Message {
static function Info($string) { echo $string; }
static function Error($string) { echo $string; }
}
//Functions
function function1($var1) {
if (!preg_match("/^[0-9]+$/", $var1)){
Message::Error($msg['Error1']);
}
when i run it, and example i test the program like this..
$test = 'blabla';
function1($test);
it says the msg variable was undefined. Can anyone tell me how to resolve this?
Thanks in advance.
There are three ways to solve this issue.
Passing the required global var as a parameter
In my opinion, this is the preferred solution, as it avoids the pollution of your function with global variables. Global variables tend to introduce unexpected side effects and make maintenance and reuse of code a lot harder. A very extensive article on why you should avoid globals whenever possible (and some alternative solutions) can be found in the c2 wiki
function function1($var1,$mesg) {
if (!preg_match("/^[0-9]+$/", $var1)){
Message::Error($mesg['Error1']);
}
}
The call to function1 changes to
function1($test,$msg);
Using global:
Same effect as the one just below, other notation.
function function1($var1) {
global $msg;
if (!preg_match("/^[0-9]+$/", $var1)){
Message::Error($msg['Error1']);
}
}
Using the $GLOBALS superglobal
Some sources say this form is slightly faster than the one using global
function function1($var1) {
if (!preg_match("/^[0-9]+$/", $var1)){
Message::Error($GLOBALS['msg']['Error1']);
}
}
you can not use $msg as a local variable in function.
function function1($var1) {
global $msg;
if (!preg_match("/^[0-9]+$/", $var1)){
Message::Error($msg['Error1']);
}
}

php function in array broken

I am trying to setup an array that pulls the filename and function name to run, but it not fully working.
The code is
$actionArray = array(
'register' => array('Register.php', 'Register'),
);
if (!isset($_REQUEST['action']) || !isset($actionArray[$_REQUEST['action']])) {
echo '<br><br>index<br><br>';
echo 'test';
exit;
}
require_once($actionArray[$_REQUEST['action']][0]);
return $actionArray[$_REQUEST['action']][1];
Register.php has
function Register()
{
echo 'register';
}
echo '<br>sdfdfsd<br>';
But it does not echo register and just sdfdfsd.
If I change the first lot of code from
return $actionArray[$_REQUEST['action']][1];
to
return Register();
It works, any ideas?
Thanks
Change the last line to:
return call_user_func($actionArray[$_REQUEST['action']][1]);
This uses the call_user_func function for more readable code and better portability. The following also should work (Only tested on PHP 5.4+)
return $actionArray[$_REQUEST['action']][1]();
It's almost the same as your code, but I'm actually invoking the function instead of returning the value of the array. Without the function invocation syntax () you're just asking PHP get to get the value of the variable (in this case, an array) and return it.
You'll find something usefull here:
How to call PHP function from string stored in a Variable
Call a function name stored in a string is what you want...

unlisted reserved word?

I ran into a very strange behaviour in some of our PHP code today. We have a class for dealing with files. It's something like this:
class AFile {
//usual constructor, set and get functions, etc.
//...
public function save() {
//do some validation
//...
if($this->upload()) { //save the file to disk
$this->update_db(); //never reached this line
}
}
private function upload() {
//save the file to disk
//...
return ($success) ? true : false;
}
}
It looked pretty normal to us, but the $this->upload() function never returned anything but NULL. We checked that the correct function was running. We echoed out its return value before it returned. We tried only returning a true value or even a string. Everything was checking out right. But $this->upload still evaluated to NULL. Also, there was nothing in the logs and ERROR_ALL is on.
In exasperation we changed the function name to foo_upload. All of a sudden everything worked. "upload" is not in the list of PHP reserved words. Anyone have any thoughts why a class function named "upload" would fail?
Make sure the return statement at the end of the upload method is the only return statement in that method.
One way to get null when "calling" upload would be if you had this (trying to access an inexisting property) :
if($a = $this->upload) { // => NULL
$this->update_db(); //never reached this line
}
var_dump($a);
instead of this (from OP) (trying to call an existing method):
if($a = $this->upload()) { // => true or false
$this->update_db(); //never reached this line
}
var_dump($a);
Did you check you didn't forget the () ?
If it's not this, try with error_reporting set to E_ALL, and displaying the errors :
ini_set('display_errors', true);
error_reporting(E_ALL);
(you said "ERROR_ALL is on", so not sure it's what you meant)

Categories