PHP变量覆盖前面的变量

时间:2017-02-02 14:06:47

标签: php class

我正在处理一个基于我的客户提供给我的模板的脚本。目标是从POST请求中收集数据,对其进行编译,然后将其发送给第三方应用程序。

数据的性质意味着通常会有一组特定变量的实例,例如当前地址,以前的地址和雇主地址。

在下面的代码中,为每种地址类型定义了一个新对象。一个简单的例子:

//set the variables from POST
$address_line_1 = $_POST['currentaddress'];
$prev_add_line_1 = $_POST['previousaddress'];
$emp_add_line_1 = $_POST['employeraddress'];

//create the request and set credentials
$request = new stdClass();
$request->request->Credentials->Username = $username;
$request->request->Credentials->Password = $password;
$request->request->Credentials->Account = $account;

//set classes for multiple address and populate with data for compiling
$address = new stdClass();
$address->AddressType = 'Current';
$address->Line1 = $address_line_1;

$address = new stdClass();
$address->AddressType = 'Previous';
$address->Line1 = $prev_add_line_1;

$address = new stdClass();
$address->AddressType = 'Employer';
$address->Line1 = $emp_add_line_1;

$customer->Addresses = array($address);
$request->request->Proposal->Customers = array($customer);

return $request;

我遇到的问题是如果提交了这个,那么最近定义的变量会覆盖前两个变量,因此它们会被忽略,因此不会被发送到第三方应用程序(请求会被拒绝)因此没有所需信息。)

此项目中还必须定义其他类型的对象,例如:

$primary_customer_name = $_POST['primaryname'];
$secondary_customer_name = $_POST['secondaryname'];

$customer = new stdClass();
$customer->CustomerType = 'Primary';
$customer->Name = $primary_customer_name;

$customer = new stdClass();
$customer->CustomerType = 'Secondary';
$customer->Name = $secondary_customer_name;

同样,这里的问题是次要客户覆盖了主要客户。

我不确定我缺少什么,希望有人可以指出我明显的明显错误。

如果需要更多信息,请告知我们,我将更新此帖。

非常感谢。

1 个答案:

答案 0 :(得分:3)

你正在编写变量。

例如:以下将$a定义为2.第二个语句将覆盖第一个语句。

$a = 1;
$a = 2;

所以你需要做的是在另一个标识符下定义附加变量。

例如:

$address = new stdClass();
$address->AddressType = 'Current';
$address->Line1 = $address_line_1;

$address2 = new stdClass();
$address2->AddressType = 'Previous';
$address2->Line1 = $address_line_1;

此外,您在创建以下数组时仅引用单个$address。您需要引用所有值:

$customer->Addresses = array($address, $address2);