Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

how to add property to an object in php

//this is my code 

lets say that we have an object with the name ($obj), 
and we want to add Properties to it, we can do many ways and some of them are:-
  
1- we can change the type of object into array using casting,
then we add elemnt to the array then we change it back to an object, like this:-
  
<?php
  $obj = (array)$obj;
        $obj['car'] = '1234';
        $obj['ball'] = 'hello';
        $obj = (object)$obj;
  var_dump($obj);
?>

then the object $obj will have new two Properties which are:-
the first one with the name car and value of '1234',
the second one with the name ball and value of 'hello'
  
2- this is a second way to do it:-
  
<?php
$obj->car = 'value1';
$obj->ball = 'value2';
var_dump($obj);
?>

then the object $obj will have new two Properties which are:-
the first one with the name car and value of 'value1',
the second one with the name ball and value of 'value2'
  
  
3- if you want to add Properties to an object but also delete or remove,
all the previous Properties of the object, then we do this:-
  
<?php
  $obj = (array)null;
        $obj['attributes'] = '1234';
        $obj['attributes'] = 'hello';
        $obj = (object)$obj;
  var_dump($obj);
?>
 
PREVIOUS NEXT
Tagged: #add #property #object #php
ADD COMMENT
Topic
Name
4+5 =