Search
 
SCRIPT & CODE EXAMPLE
 

PHP

how to add attributes 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 :: e_notice in php 
Php :: how to get a particular column in laravel 8 
Php :: php foreach 
Php :: woocommerce get variation price range 
Php :: Laravel Validation error message in blade or view 
Php :: How do I check if a string contains a specific word? 
Php :: get full current url in laravel 
Php :: how to backup laravel project 
Php :: ubuntu install lamp and phpmyadmin 
Php :: how to display user id from a function on a wordpress page 
Php :: setinterval php 
Php :: Custom Product Price in Loop of Woocomare 
Php :: get the current date and time in php 
Php :: php read csv to array 
Php :: How to call soap api in php using curl method 
Php :: To perform the requested action, WordPress needs to access your web server. Please enter your FTP 
Php :: get url link in php 
Php :: parameterized function in php 
Php :: 404 page in laravel 
Php :: PHP (WordPress) - Increase Maximum Upload File Size 
Php :: php export excel 
Php :: laravel group route controller 
Php :: php combine arrays 
Php :: 18 year back date in php 
Php :: database collection to array 
Php :: laravel get auth user id 
Php :: image store short method in laravel 
Php :: how to set date in php 
Php :: store image in storage laravel 
Php :: PHP Function to create GUID 
ADD CONTENT
Topic
Content
Source link
Name
8+3 =