Search
 
SCRIPT & CODE EXAMPLE
 

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);
?>
Comment

php add property to object

$foo = (array)$foo;
$foo['bar'] = '1234';
$foo = (object)$foo;
Comment

PREVIOUS NEXT
Code Example
Php :: laravel blade variable isset, empty or optional 
Php :: php enter line break 
Php :: php echo array 
Php :: php date start of day 
Php :: laravel dump query 
Php :: laravel validate enum field 
Php :: php randon integer 4 digit 
Php :: php timer 
Php :: Undefined index: HTTP_HOST 
Php :: php generate slug 
Php :: date and time in php 
Php :: make model inside module laravel 
Php :: how to delete all products woocommerce in phpmyadmin 
Php :: auth laravel 9 
Php :: PHP time limit (max_execution_time): 
Php :: set session after login with laravel 
Php :: php declare strict_types 
Php :: csrf token mismatch laravel api 
Php :: php check request method 
Php :: laravel set config value dynamically 
Php :: laravel insert timestamp now 
Php :: php check connection to database 
Php :: migrate specific file laravel 
Php :: laravel model update 
Php :: php info 
Php :: validation not exist in table laravel 
Php :: php get current dir mac 
Php :: str_contains 
Php :: php datetime sub minutes 
Php :: random string generator php 
ADD CONTENT
Topic
Content
Source link
Name
3+6 =