Search
 
SCRIPT & CODE EXAMPLE
 

PHP

how to add property to an exsisting 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);
?>
Comment

PREVIOUS NEXT
Code Example
Php :: how to add property to an object in php 
Php :: Allowed memory size of 1610612736 bytes exhausted (tried to allocate 4096 bytes) in phar:///usr/local/bin/composer/src/Composer/DependencyResolver/RuleWatchGraph.php on line 52 
Php :: write in a file using php 
Php :: laravel eloquent where id not equal to 
Php :: How to create a controller in laravel 
Php :: twig filter line break 
Php :: php array json encode key and value 
Php :: laravel where not 
Php :: remove whitespace from string php 
Php :: create slug with php 
Php :: laravel limit foreach 
Php :: upload webp to wordpress 
Php :: woocommerce bulk product delete 
Php :: php expire session 
Php :: laravel 404 
Php :: minus day from carbon date 
Php :: php split array in half 
Php :: laravel elasticsearch migration in laravel 
Php :: require_once php 
Php :: how to use postgresql with laravel 
Php :: php date from format 
Php :: populate old value of dropdown laravel 
Php :: php send telegram message to user 
Php :: php sort array by value length 
Php :: display time php 
Php :: laravel asset 
Php :: remove non-uppercase character php 
Php :: Exception #0 (MagentoFrameworkExceptionValidatorException): Invalid template file: 
Php :: how to go to another folder in php 
Php :: php return a json response 
ADD CONTENT
Topic
Content
Source link
Name
5+8 =