简体   繁体   English

PHP将数组传递给类函数

[英]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 我可以通过$ result [0]获得,我想通过价值获得它,谢谢

The way your code is written, if my name is Jay and I am 31 years old, the array will look like this... 编写代码的方式,如果我叫Jay ,今年31岁,则数组看起来像这样...

{
'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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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