[英]how to do PHP object reference with an arrow pointer operator to a dynamically generated value
I want to be able to do an object reference with a pointer operator to a dynamically generated value 我希望能够使用指针运算符对动态生成的值进行对象引用
//Jobs
class Jobs
{
private $orderid;
private $quantity;
private $contactno;
private $contactname;
}
Hence I will create object keys 因此,我将创建对象键
$keys = array(
'orderid',
'quantity',
'contactno',
'contactname'
);
Then do 然后做
$size = 4;
$i = 0;
//object instantiation
$jobObject = new Jobs();
$row = array('894949','45','08097577580','Emi');
for($i=0;$i<$size;$i++){
//This is my challenge
$jobObject->$keys[$i] = $row[$i];
}
I am very sure there should be a way to get the value of $keys[$i] that can be referenced by "$jobObject->" to do object property initialization. 我非常确定应该有一种方法可以获取可以由“ $ jobObject->”引用的$ keys [$ i]的值来进行对象属性初始化。
I have tried to enclose $keys[$i] with braces by doing 我试图通过用大括号括起来$ keys [$ i]
$jobObject->{$keys[$i]} = $row[$i];
Yet it throws error. 但是它会引发错误。 Please I need help on how to get this working or a way out.
请我帮忙解决此问题或寻求帮助。
You cannot assign a value directly to a protected property. 您不能直接将值分配给受保护的属性。 Take a look to visibility reference .
看一下能见度参考 。
The correct way to achieve what you want is the following. 以下是实现所需目标的正确方法。
<?php
class Jobs
{
// Change access to public
public $orderid;
public $quantity;
public $contactno;
public $contactname;
}
$keys = array(
'orderid',
'quantity',
'contactno',
'contactname'
);
$size = 4;
$i = 0;
//object instantiation
$jobObject = new Jobs();
$row = array('894949','45','08097577580','Emi');
for($i=0;$i<$size;$i++){
// This is the way
$jobObject->{$keys[$i]} = $row[$i];
}
var_dump($jobObject);
You have to use brackets for variable variables. 您必须对变量使用方括号。 You'll then be able to dynamically create your object:
然后,您将能够动态创建对象:
$jobObject->{$keys[$i]} = $row[$i];
Take a look at the php documentation this subject: http://php.net/manual/en/language.variables.variable.php 看看这个主题的php文档: http : //php.net/manual/zh/language.variables.variable.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.