Why this variable act as a object? - php

I am very new in programming world. It may it's a very silly question. But I need a clear concept about this issue that's why I am asking this question.
<?php
$json = '{"a":1}';
$data = json_decode($json);
echo $data->a;
?>
I have learn when we called a object that should be
$data = new json_decode($json);
Why this $data worked as a object without new ?

That is a json array, it can be converted to an object or to an associative array.
If you use the function
$object = json_decode($array);
the destination variable will be treated as an object.
If your will is just to decode to a json array to an associative array you have to add a true after the array
$assArray= json_decode($array,true);
In this case you can access the values as a normal array
echo($assArray["a"]);
Will output 1.
However I suggest you to check the official manual, is very clear in the explanation of these function
PHP Official manual json_decode

You need to store it inside a variable to use like an array.
<?php
$json = '{"a":1}';
$data = json_decode($json,true);
echo $data['a'];
?>

By default json_decode (without providing second parameter) will return you object, which means that the function itself will create (and return) new stdClass for you.
If you want array instead:
$data = json_decode($json, true);

It's because you use a function that returning an instance.
When you use new operator, you create an instance explicitely from className. With examples :
function return_instance() {
return new ClassName();
}
$obj1 = return_instance();
$obj2 = new ClassName();
// The two objects return the same type of object

json_decode by default attempts to return an object rather than an array. In doing so you don't need to new json_decode, rather just call the function directly. You can return an array by adding a second parameter true.
For example:
$asObject = json_decode($jsonText);
$asArray = json_decode($jsonText, true);
The new keyword essentially invokes a class's constructor to create a new object. If you like, you can think of json_decode as calling new inside the function so to create a new object for you.

becouse json_deocde return type is of object type here is example
function jsonDecode($json){
//here logic of decoding;
return new stdClass();
}
now it will type of object

Related

How to convert an object properties into an array in php

Those data in $data variable. When I'm using dd($data); I got this:
CurlHandle {#1918 ▼
+url: "https://example.com"
+content_type: "application/json; charset=UTF-8"
+http_code: 200
+header_size: 887
+namelookup_time_us: 139522
+pretransfer_time_us: 326662
+redirect_time_us: 0
+starttransfer_time_us: 668686
+total_time_us: 668752
}
I want to convert this data to an array.
I'm using this: $arr = json_decode($data,true);
But, this is not working. Now, how can I convert this?
You can use below solution
$yourArray = json_decode(json_encode($yourObject), true);
and this convert object to an array for more info
Objects are, in PHP, maybe iterable. Notice, you may iterate through an object's public fields only via the foreach loop. So the following works:
$array = [];
foreach ($object as $property) {
$array[] = $property; // Stores public field only
}
var_dump($array);
Simply to get an array of object properties, you may use the get_object_vars() function.
var_dump(get_object_vars($object));
You may cast an object to be an array as #MoussabKbeisy said. And this would be the easiest way:
$array = (array) $object;
Here is another way is using ArrayIterator:
$iterator = new ArrayIterator($object);
var_dump(iterator_to_array($iterator));
while this is a PHP Object so you can deal with it by 2 ways:
1- if you want to get on of it's parameters, you can simply use
$yourObject->parameter;
2- if you need to use convert and use it as array, then there is different ways to convert an object to an array in PHP
//1
$array = (array) $yourObject;
//2
$array = json_decode(json_encode($yourObject), true);
Also see this in-depth blog post:
Fast PHP Object to Array conversion

Problem retrieve JSON data from PHP as object [duplicate]

I have this code
$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=>array(),
);
echo json_encode($status);
This function return json:
{"message":"error","club_id":275,"status":"1","membership_info":[]}
But I need json like this:
{"message":"error","club_id":275,"status":"1","membership_info":{}}
use the JSON_FORCE_OBJECT option of json_encode:
json_encode($status, JSON_FORCE_OBJECT);
Documentation
JSON_FORCE_OBJECT (integer)
Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. Available since PHP 5.3.0.
Or, if you want to preserve your "other" arrays inside your object, don't use the previous answer, just use this:
$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=> new stdClass()
);
$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=>(object) array(),
);
By casting the array into an object, json_encode will always use braces instead of brackets for the value (even when empty).
This is useful when can't use JSON_FORCE_OBJECT and when you can't (or don't want) to use an actual object for the value.
There's no difference in PHP between an array and an "object" (in the JSON sense of the word). If you want to force all arrays to be encoded as JSON objects, set the JSON_FORCE_OBJECT flag, available since PHP 5.3. See http://php.net/json_encode. Note that this will apply to all arrays.
Alternatively you could actually use objects in your PHP code instead of arrays:
$data = new stdClass;
$data->foo = 'bar';
...
Maybe it's simpler to handle the edge case of empty arrays client-side.
I know this is an old question, but it's among the first hits on Google, so I thought I should share an alternative solution.
Rather than using standard PHP arrays, in PHP 7+ you can instead use Map() as part of the Data Structure extension. Documentation.
A Map object has practically identical performance as arrays and also implements ArrayAccess so it can be accessed as a regular array. Contrary to a standard array, however, it will always be associative and works as expected with json_encode. It also has some other minor benefits like object keys and better memory handling.
Some example usage:
use Ds\Map;
$status = new Map([
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=>array(),
]);
$map = new Map();
print json_encode($map); // {}
$map = new Map();
$map["foo"] = "bar";
print json_encode($map); // {"foo":"bar"}
print $map["foo"]; // bar
$map = new Map();
$map[1] = "foo";
$map[2] = "bar";
$map[3] = "baz";
print json_encode($map); // {"1":"foo","2":"bar","3":"baz"}
While this may not be considered elegant, a simple string replace can effectively address this.
str_replace("[]", "{}", json_encode($data));
This mitigates the issue of JSON_FORCE_OBJECT converting a normal array into an object.

json_encode function not return Braces {} when array is empty in php

I have this code
$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=>array(),
);
echo json_encode($status);
This function return json:
{"message":"error","club_id":275,"status":"1","membership_info":[]}
But I need json like this:
{"message":"error","club_id":275,"status":"1","membership_info":{}}
use the JSON_FORCE_OBJECT option of json_encode:
json_encode($status, JSON_FORCE_OBJECT);
Documentation
JSON_FORCE_OBJECT (integer)
Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. Available since PHP 5.3.0.
Or, if you want to preserve your "other" arrays inside your object, don't use the previous answer, just use this:
$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=> new stdClass()
);
$status = array(
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=>(object) array(),
);
By casting the array into an object, json_encode will always use braces instead of brackets for the value (even when empty).
This is useful when can't use JSON_FORCE_OBJECT and when you can't (or don't want) to use an actual object for the value.
There's no difference in PHP between an array and an "object" (in the JSON sense of the word). If you want to force all arrays to be encoded as JSON objects, set the JSON_FORCE_OBJECT flag, available since PHP 5.3. See http://php.net/json_encode. Note that this will apply to all arrays.
Alternatively you could actually use objects in your PHP code instead of arrays:
$data = new stdClass;
$data->foo = 'bar';
...
Maybe it's simpler to handle the edge case of empty arrays client-side.
I know this is an old question, but it's among the first hits on Google, so I thought I should share an alternative solution.
Rather than using standard PHP arrays, in PHP 7+ you can instead use Map() as part of the Data Structure extension. Documentation.
A Map object has practically identical performance as arrays and also implements ArrayAccess so it can be accessed as a regular array. Contrary to a standard array, however, it will always be associative and works as expected with json_encode. It also has some other minor benefits like object keys and better memory handling.
Some example usage:
use Ds\Map;
$status = new Map([
"message"=>"error",
"club_id"=>$_club_id,
"status"=>"1",
"membership_info"=>array(),
]);
$map = new Map();
print json_encode($map); // {}
$map = new Map();
$map["foo"] = "bar";
print json_encode($map); // {"foo":"bar"}
print $map["foo"]; // bar
$map = new Map();
$map[1] = "foo";
$map[2] = "bar";
$map[3] = "baz";
print json_encode($map); // {"1":"foo","2":"bar","3":"baz"}
While this may not be considered elegant, a simple string replace can effectively address this.
str_replace("[]", "{}", json_encode($data));
This mitigates the issue of JSON_FORCE_OBJECT converting a normal array into an object.

Fetching an object in Mongo PHP library

I use this MongoDB library for PHP
If I use this code:
$db->users->find();
I get an associative array.
Is it possible to get an object as a result of find() method?
For example, in PDO I can do it like this:
$stmt->fetch(PDO::FETCH_OBJ);
Thank you.
If all you're looking for is an stdclass object (like with PDO::FETCH_OBJ), you can cast the current element:
$obj = (object) $db->users->find()->getNext();
Learn more about casting in the PHP manual:
Type Juggling (PHP Manual)
The call
$db->users->find();
returns a \MongoCursor object, which is an iterator you can loop over in a foreach loop as you would with an array. But each result you get from it, though, is an associative array.
http://php.net/mongocollection.find
So, to get objects instead you could cast each item to object prior to using it :
$list = $db->users->find();
foreach($list as $user) {
$user = (object)$user; // object cast here
echo $user->name; // use it as an object
}

Does PHP feature short hand syntax for objects?

In javascript you can easily create objects and Arrays like so:
var aObject = { foo:'bla', bar:2 };
var anArray = ['foo', 'bar', 2];
Are similar things possible in PHP?
I know that you can easily create an array using the array function, that hardly is more work then the javascript syntax, but is there a similar syntax for creating objects? Or should I just use associative arrays?
$anArray = array('foo', 'bar', 2);
$anObjectLikeAssociativeArray = array('foo'=>'bla',
'bar'=>2);
So to summarize:
Does PHP have javascript like object creation or should I just use associative arrays?
For simple objects, you can use the associative array syntax and casting to get an object:
<?php
$obj = (object)array('foo' => 'bar');
echo $obj->foo; // yields "bar"
But looking at that you can easily see how useless it is (you would just leave it as an associative array if your structure was that simple).
There was a proposal to implement this array syntax. But it was declined.
Update    The shortened syntax for arrays has been rediscussed, accepted, and is now on the way be released with PHP 5.4.
But there still is no shorthand for objects. You will probably need to explicitly cast to object:
$obj = (object) ['foo'=>'bla', 'bar'=>2];
As of PHP 5.4, you can do this:
$array = ['foo'=>'bla', 'bar'=>2];
It's not much shorter, but you'll appreciate it if you need to use a lot of hard coded nested arrays (which isn't altogether uncommon).
If you want an object, you would still need to cast each array:
$object = (object) ['foo'=>'bla', 'bar'=>2];
According to the new PHP syntaxes,
You can use
$array = [1,2,3];
And for associative arrays
$array = ['name'=>'Sanket','age'=>22];
For objects you can typecast the array to object
$object = (object)['name'=>'Sanket','age'=>22];
There is no object shorthand in PHP, but you can use Javascript's exact syntax, provided you use the json_encode and json_decode functions.
The method provided by crescentfresh works very well but I had a problem appending more properties to the object. to get around this problem I implemented the spl ArrayObject.
class ObjectParameter extends ArrayObject {
public function __set($name, $value) {
$this->$name = $value;
}
public function __get($name) {
return $this[$name];
}
}
//creating a new Array object
$objParam = new ObjectParameter;
//adding properties
$objParam->strName = "foo";
//print name
printf($objParam->strName);
//add another property
$objParam->strUser = "bar";
There is a lot you can do with this approach to make it easy for you to create objects even from arrays, hope this helps .
Like the json_decode idea, wrote this:
function a($json) {
return json_decode($json, true); //turn true to false to use objets instead of associative arrays
}
//EXAMPLE
$cat = 'meow';
$array = a('{"value1":"Tester",
"value2":"'.$cat.'",
"value3":{"valueX":"Hi"}}');
print_r($array);

Categories