Home > Software design >  In PHP, how can I set an array in an object value
In PHP, how can I set an array in an object value

Time:04-21

I'm using PHP. I have an array of values and i need set this value in a object

$objAcessoExternoParticipanteDTO = new AcessoExternoDTO();
$objAcessoExternoParticipanteDTO->setNumIdAtividade($myArray);
array(49) {
  [0]=>
  string(5) "25208"
  [1]=>
  string(5) "25230"
  [2]=>
  string(5) "25239"
  [3]=>
  string(5) "25242"
  [4]=>
  string(5) "25243"
  [5]=>
  string(5) "25244"
  [6]=>
  string(5) "25247"
  [7]=>
  string(5) "25250"
  [8]=>
  string(5) "25251"
  [9]=>
  string(5) "25252"
}

$myArray is what i'm trying to pass, is it possible?

CodePudding user response:

If you want an instance of this object containing each of the values from the array you will either have to create count($myArray) uniquely named objects (which could get very messy very quickly) or store all the objects in another array, like this

class AcessoExternoDTO
{
    private $NumIdAtividade;

    public function SetNumIdAtividade($v)
    {
        $this->NumIdAtividade = $v;
    }
}

$myArray= [ "25208", "25230", "25239", "25242", "25243", "25244", "25247", "25250"];

$objArr = [];
foreach ( $myArrayas $value){
    $obj = new AcessoExternoDTO;
    $obj->SetNumIdAtividade($value);
    $objArr[] = $obj;
}

print_r($objArr);

RESULT

Array
(
    [0] => AcessoExternoDTO Object
        (
            [NumIdAtividade:AcessoExternoDTO:private] => 25208
        )
    [1] => AcessoExternoDTO Object
        (
            [NumIdAtividade:AcessoExternoDTO:private] => 25230
        )
    [2] => AcessoExternoDTO Object
        (
            [NumIdAtividade:AcessoExternoDTO:private] => 25239
        )
    [3] => AcessoExternoDTO Object
        (
            [NumIdAtividade:AcessoExternoDTO:private] => 25242
        )
    [4] => AcessoExternoDTO Object
        (
            [NumIdAtividade:AcessoExternoDTO:private] => 25243
        )
    [5] => AcessoExternoDTO Object
        (
            [NumIdAtividade:AcessoExternoDTO:private] => 25244
        )
    [6] => AcessoExternoDTO Object
        (
            [NumIdAtividade:AcessoExternoDTO:private] => 25247
        )
    [7] => AcessoExternoDTO Object
        (
            [NumIdAtividade:AcessoExternoDTO:private] => 25250
        )

)
  • Related