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 attributes to an object in php 
Php :: how to use wherein in json array laravel 
Php :: how to get a particular column in laravel 8 
Php :: yii app db createcommand join yii1 
Php :: carbon difference between two dates 
Php :: laravel get route in unauthenticated 
Php :: laravel group routes 
Php :: php run localhost 
Php :: wordpress plugin add stylesheet 
Php :: https redirect in htacess for php laravel 
Php :: how to get data from html form in php 
Php :: phpspreadsheet middle align 
Php :: laravel in array blade 
Php :: sum of columns laravel eloquent 
Php :: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known 
Php :: php in html attributes 
Php :: php file put content 
Php :: phpcs 
Php :: php check if input is int 
Php :: laravel get request check 
Php :: how assign default value to laravel migration column 
Php :: how to convert array to string in php 
Php :: wordpress get current taxonomy 
Php :: how to start laravel project 
Php :: laravel query latest 
Php :: how to get a whole number from decimal in php 
Php :: laravel 8 get app folder 
Php :: reload page laravel 
Php :: get text field value in php 
Php :: show alert in php 
ADD CONTENT
Topic
Content
Source link
Name
7+5 =