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 :: offset codeigniter 3 
Php :: pluck array in laravel 
Php :: hasone relation in laravel 
Php :: clear laravel.log 
Php :: paginate relationship laravel7 
Php :: php remove and  
Php :: string to boolean php 
Php :: implode and explode in php 
Php :: laravel check if object is empty 
Php :: insert data in database using seeder in laravel 
Php :: laravel createmany example 
Php :: laravel custom log 
Php :: custom 404 page in laravel 
Php :: laravel forcefill 
Php :: laravel add crf token form 
Php :: php remove array element 
Php :: PHP Forms - Required Fields 
Php :: laravel 8 make model with migration and controller 
Php :: web api return json example in php 
Php :: laravel blade empty 
Php :: pdf to html php 
Php :: convert text file to json php 
Php :: eloquent limit 
Php :: codeigniter 4 limit query 
Php :: wp shortcode 
Php :: Add ... if string is too long PHP 
Php :: get post by name wordpress 
Php :: wordpress get order 
Php :: laravel validate datetime with datetime-local 
Php :: laravel collection concat 
ADD CONTENT
Topic
Content
Source link
Name
8+9 =