简体   繁体   中英

php passing array to class function

Hello i want to pass array to my class function but i am not getting the value . plz help me out what is the problem with this sample code

 <?php
if(isset($_POST['submituser']))
{
$user = new User();
$user->connect();
$name=$_POST['name'];
$age=$_POST['age'];

$result = array($name=>$name,$age=>$age);


$user->setUser($result);

$user->disconnect();
}
?>

and the class function is like this

function setUser($result) 
{
echo $result[$name];
$errors_all = array();
$validate = new Validator();
$validate->addRequiredFieldValidator($result[$name],"First name is required.")."";
}

i can get by $result[0] by i want to get it by value Thanks

The way your code is written, if my name is Jay and I am 31 years old, the array will look like this...

{
'Jay' => 'Jay',
'31' => 31
}

The keys should be constant strings, and not (in this case) variables, as indicated by the $ sign.

Try this instead.

$result = array(
    'name'=>$name,
    'age'=>$age
);

This will yield

{
'name' => 'Jay',
'age' => 31
}

Important you must also change the way you are echo'ing your array values

//echo $result[$name];
echo $result['name'];

When passing it, you should not have the $ in the array key. Instead they should be quoted strings:

// Incorrect:
$result = array($name=>$name,$age=>$age);

// Should be:
$result = array('name'=>$name,'age'=>$age);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM