How to define an empty object in PHP
$x = new stdClass();
A comment in the manual sums it up best:
stdClass is the default PHP object.
stdClass has no properties, methods or
parent. It does not support magic
methods, and implements no interfaces.When you cast a scalar or array as
Object, you get an instance of
stdClass. You can use stdClass
whenever you need a generic object
instance.
create an empty object in JSON with PHP?
Try This
$cc['CC'] = new stdClass ;
echo json_encode($jsonrows['paymentmethods']=$cc);
Output is
{"CC":{}}
Best way to create an empty object in JSON with PHP?
If you use objects as dynamic dictionaries (and I guess you do), then I think you want to use an ArrayObject.
It maps into JSON dictionary even when it's empty. It is great if you need to distinguish between lists (arrays) and dictionaries (associative arrays):
$complex = array('list' => array(), 'dict' => new ArrayObject());
print json_encode($complex); // -> {"list":[],"dict":{}}
You can also manipulate it seamlessly (as you would do with an associative array), and it will keep rendering properly into a dictionary:
$complex['dict']['a'] = 123;
print json_encode($complex); // -> {"list":[],"dict":{"a":123}}
unset($complex['dict']['a']);
print json_encode($complex); // -> {"list":[],"dict":{}}
If you need this to be 100% compatible both ways, you can also wrap json_decode
so that it returns ArrayObjects
instead of stdClass
objects (you'll need to walk the result tree and recursively replace all the objects, which is a fairly easy task).
Gotchas. Only one I've found so far: is_array(new ArrayObject())
evaluates to false
. You need to find and replace is_array
occurrences with is_iterable
.
How can I create Object in PHP?
Here is a solution
$newObject = new stdClass;
$newObject->ERROR_CODE = 0;
$newObject->M_USER = new stdClass;
$newObject->M_USER->CREATE_DATE = "2018-05-09 13:57:49";
And so on.
Creating default object from empty value in PHP?
Your new environment may have E_STRICT
warnings enabled in error_reporting
for PHP versions <= 5.3.x, or simply have error_reporting
set to at least E_WARNING
with PHP versions >= 5.4. That error is triggered when $res
is NULL
or not yet initialized:
$res = NULL;
$res->success = false; // Warning: Creating default object from empty value
PHP will report a different error message if $res
is already initialized to some value but is not an object:
$res = 33;
$res->success = false; // Warning: Attempt to assign property of non-object
In order to comply with E_STRICT
standards prior to PHP 5.4, or the normal E_WARNING
error level in PHP >= 5.4, assuming you are trying to create a generic object and assign the property success
, you need to declare $res
as an object of stdClass
in the global namespace:
$res = new \stdClass();
$res->success = false;
Singleton pattern in my php project returns an empty object in second time
The issue resides in the Db class definition. The first time you called conDb
it returned a new Db object that then assigned the static variable a PDO object.
The second time you call that method you get back a PDO object which made the if guard evaluate to false, since a Db object and PDO object are different. In case you call it more than 2 times the objects returned thereafter would be PDO objects and tested for true.
Below a suggested change to the Db class.
class Db
{
private $dsn = 'mysql:host=localhost;dbname=test';
private $user = 'root';
private $password = '6ReA4';
private $options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
private static $PDO = null;
private function __clone()
{
}
private function __wakeup()
{
}
public static function conDb()
{
// This is always null the first call
if (is_null(self::$PDO)) {
// Here you returned a new Db object.
// return new self(); // <- old line.
try {
self::$PDO = new \PDO($this->dsn, $this->user, $this->password, $this->options);
} catch (\PDOexception $e) {
"Date base connection error " . $e->getMessage();
}
}
// Here you returned a PDO object in an else, this can just be the variable after the PDO object is created.
return self::$PDO;
}
}
In the construction of the Model, the if would evaluate to false testing a Db object vs a PDO object.
public function __construct()
{
$this->db2 = Db::conDb();
$this->db = Db::conDb();
if ($this->db == $this->db2) {
echo "Singleton works";
} else {
echo "Fail";
}
}
Javascript empty array and empty object equivalent in PHP
The first one is an Array of one element, being the element an empty string. In PHP it'd be [""]
or array("")
.
<?php
$a = [""];
var_dump($a); // array(1) { [0]=> string(0) "" }
$b = array("");
var_dump($b); // array(1) { [0]=> string(0) "" }
The second is an object with empty string value for key 0
. In PHP it could be represented as: (object)[""]
or (object)[0 => ""]
.
<?php
$a = (object)[""];
var_dump($a); // object(stdClass)#1 (1) { [0]=> string(0) "" }
$b = (object)[0=>""];
var_dump($b); // object(stdClass)#2 (1) { [0]=> string(0) "" }
// Also:
$c = new \stdClass;
$c->{0} = "";
var_dump($c); // object(stdClass)#3 (1) { ["0"]=> string(0) "" }
Please, read about PHP Arrays and PHP Objects.
Is there a way to set object parameter value to empty string if object does not exist in php
You have a few different options
The long way is using one of the following functions in an if statement:
- isset
- empty
example
if(!isset($car->name)) {
return 'No car';
}
using empty
if(empty($car->name)) {
return 'No car';
}
Or you can combine both if you really wanted.
You can also use them in shorthand as you have done above or using the isset and or empty functions.
If you are using PHP version 7 you can use a new feature that shipped with it called Null coalescing operator (??)
Example:
echo $car->name ?? 'No car';
It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
I am running PHP7 and use it daily!
Related Topics
What Does This Mean in PHP: -> or =>
Phpexcel Auto Size Column Width
What Do the Ent_Html5, Ent_Html401, ... Modifiers on HTML_Entity_Decode Do
How to Exclude Certains Columns While Using Eloquent
Compile a Referenced Less File into CSS with PHP Automatically
Laravel 5 - After Login Redirect Back to Previous Page
How to Keep JSON_Encode() from Dropping Strings with Invalid Characters
Changing the Root Folder via .Htaccess
Get All MySQL Selected Rows into an Array
Parse JSON String Contents into PHP Array
Asynchronous Function Call in PHP
.Htaccess 301 Redirect of Single Page
Get Value of Dynamically Chosen Class Constant in PHP
Laravel 5.4 Field Doesn't Have a Default Value
Delete First 3 Characters and Last 3 Characters from String PHP
Aws Cloudfront + Load Balancer, Url Changes from Main Domain to Load Balancer Subdomain