php create empty object
How to define an empty object in PHP
with a new array I do this:
Is there a similar syntax for an object
17 Answers 17
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.
The standard way to create an «empty» object is:
But I personally prefer to use:
It’s shorter and I personally consider it clearer because stdClass could be misleading to novice programmers (i.e. «Hey, I want an object, not a class!». ).
See the PHP manual (here):
stdClass: Created by typecasting to object.
If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created.
and here (starting with PHP 7.3.0, var_export() exports an object casting an array with (object) ):
However remember that empty($oVal) returns false, as @PaulP said:
Objects with no properties are no longer considered empty.
Regarding your example, if you write:
PHP key1 (an object itself)
Warning: Creating default object from empty value
PHP >= 8 creates the following Error:
Fatal error: Uncaught Error: Undefined constant «key1»
In my opinion your best option is:
I want to point out that in PHP there is no such thing like empty object in sense:
On other hand empty array mean empty in both cases
Quote from changelog function empty
Objects with no properties are no longer considered empty.
Short answer
Long answer
I love how easy is to create objects of anonymous type in JavaScript:
So I always try to write this kind of objects in PHP like javascript does:
But as this is basically an array you can’t do things like assign anonymous functions to a property like js does:
Well, you can do it, but IMO isn’t practical / clean:
Also, using this synthax you can find some funny surprises, but works fine for most cases.
php.net said it is best:
In addition to zombat’s answer if you keep forgetting stdClass
You can use new stdClass() (which is recommended):
Or you can convert an empty array to an object which produces a new empty instance of the stdClass built-in class:
Or you can convert the null value to an object which produces a new empty instance of the stdClass built-in class:
Use a generic object and map key value pairs to it.
Or cast an array into an object
to access data in a stdClass in similar fashion you do with an asociative array just use the <$var>syntax.
As others have pointed out, you can use stdClass. However I think it is cleaner without the (), like so:
However based on the question, it seems like what you really want is to be able to add properties to an object on the fly. You don’t need to use stdClass for that, although you can. Really you can use any class. Just create an object instance of any class and start setting properties. I like to create my own class whose name is simply o with some basic extended functionality that I like to use in these cases and is nice for extending from other classes. Basically it is my own base object class. I also like to have a function simply named o(). Like so:
This is a great start for a base «language» to build other language layers upon with the top layer being written in full internal DSLs. This is similar to the lisp style of development, and PHP supports it way better than most people realize. I realize this is a bit of a tangent for the question, but the question touches on what I think is the base for fully utilizing the power of PHP.
Best way to create an empty object in JSON with PHP?
To create an empty JSON object I do usually use:
casting null to an object works, but is there any other preferable way and/or any problem with this solution?
7 Answers 7
Your solution could work..
The documentation specifies that (object) null will result in an empty object, some might therefor say that your code is valid and that it’s the method to use.
If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty.
.. but, try to keep it safe!
Though you never know when/if the above will change, so if you’d like to be 100% certain that you will always will end up with a <> in your encoded data you could use a hack such as:
Even though it’s tedious and ugly I do assume/hope that json_encode/json_decode is compatible with one and other and always will evaluate the following to true:
Recommended method
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):
You can also manipulate it seamlessly (as you would do with an associative array), and it will keep rendering properly into a dictionary:
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).
Php create empty object
class foo
<
function do_foo ()
<
echo «Код foo.» ;
>
>
Полное рассмотрение производится в разделе Классы и Объекты.
Преобразование в объект
При преобразовании любого другого значения, оно будет помещено в поле с именем scalar соответствующему типу.
User Contributed Notes 28 notes
By far the easiest and correct way to instantiate an empty generic php object that you can then modify for whatever purpose you choose:
In PHP 7 there are a few ways to create an empty object:
= new \ stdClass ; // Instantiate stdClass object
$obj2 = new class<>; // Instantiate anonymous class
$obj3 = (object)[]; // Cast empty array to object
As of PHP 5.4, we can create stdClass objects with some properties and values using the more beautiful form:
Here a new updated version of ‘stdObject’ class. It’s very useful when extends to controller on MVC design pattern, user can create it’s own class.
echo «‘ ;
?>
works and displays:
stdClass Object
(
[a] => A
[b] => B
[0] => C
)
/**
* Used for checking empty objects/array
* @uses How to check empty objects and array in php code
* @author Aditya Mehrotra
*/
/**
* Empty class
*/
class EmptyClass <
$obj = new stdClass ();
//or any other class empty object
$emptyClassObj = new EmptyClass ();
$array = array();
//Result SET 1
//array is empty => expected result
//object is not empty => ouch what happened
//EmptyClass is not empty => ouch what happened
/**
* So what we do for checking empty object
* @solution use any known property or check property count
* Or you can use below method
* Count function will not return 0 in empty object
*/
//Result SET 2
//array is empty => expected result ##everything is all right
//object is empty => expected result ##everything is all right
//EmptyClass is empty => expected result ##everything is all right
If you use new to create items in an array, you may not get the results you want since the parameters to array will be copies of the original and not references.
This is extremely important if you intend on passing arrays of classes to functions and expect them to always use the same object instance!
Note: The following syntax is desired (or maybe even the default notation should translate as this):
$a = array( &new Store() );
Do you remember some JavaScript implementations?
// var timestamp = (new Date).getTime();
Now it’s possible with PHP 5.4.*;
print (new Foo )-> a ; // I’m a!
print (new Foo )-> getB (); // I’m b!
?>
or
In response to sirbinam.
You cannot call a function or method before it exists. In your example, the global instance of stdout is just being passed around to differnet references (pointers). It however exists in the «dump» function scope via the global keyword.
The code below works fine and illustrates that «stdout» has been defined before its instantiation.
?>
All classes and functions declarations within a scope exist even before the php execution reaches them. It does not matter if you have your classes defined on the first or last line, as long as they are in the same scope as where they are called and are not in a conditional statement that has not been evaluated yet.
If you need to force json_encode() to produce an object even when an array is empty or does not have successive 0-based numeric indices, you can simply convert the array to an object. JSON_FORCE_OBJECT does the same with ALL arrays, which might not be what you want.
echo json_encode ([[]]), «\n» ;
// output: [[]]
echo json_encode ([[]], JSON_FORCE_OBJECT ), «\n» ;
// output: <"0":<>>
echo json_encode ([(object)[]]), «\n» ;
// output: [<>]
in php 7.2 this code works despite documentation said it gives false
= (object) array( ‘1’ => ‘foo’ );
In PHP 5+, objects are passed by reference. This has got me into trouble in the past when I’ve tried to make arrays of objects.
For example, I once wrote something like the following code, thinking that I’d get an array of distinct objects. However, this is wrong. This code will create an array of multiple references to the same object.
notice that the value at each index in the array is the same. That is because the array is just 3 references to the same object, but we change the property of this object every time the for loop runs. This isn’t very useful. Instead, I’ve changed the code below so that it will create an array with three distinct references to three distinct objects. (if you’re having a hard time understanding references, think of this as an array of objects, and that this is just the syntax you have to use.)
Notice how the creation of a new object («$arrayItem = new myNumber();») must happen every time the for loop runs for this to work.
This took me forever to figure out, so I hope this helps someone else.
PHP supports recursive type definitions as far as I’ve tried. The class below (a _very_ simple tree) is an example:
As you can see, in addChild we reference Tree again.
However, you must be careful about references. See the chapter «References explained» for more details.
If you call var_export() on an instance of stdClass, it attempts to export it using ::__set_state(), which, for some reason, is not implemented in stdClass.
However, casting an associative array to an object usually produces the same effect (at least, it does in my case). So I wrote an improved_var_export() function to convert instances of stdClass to (object) array () calls. If you choose to export objects of any other class, I’d advise you to implement ::__set_state().
/* Output:
(object) array (‘prop1’ => true, ‘prop2’ => (object) array (‘test’ => ‘abc’, ‘other’ => 6.2, ‘arr’ => array (0 => 1, 1 => 2, 2 => 3)), ‘assocArray’ => array (‘apple’ => ‘good’, ‘orange’ => ‘great’))
*/
?>
Note: This function spits out a single line of code, which is useful to save in a cache file to include/eval. It isn’t formatted for readability. If you want to print a readable version for debugging purposes, then I would suggest print_r() or var_dump().
Лучший способ создать пустой объект в JSON с PHP?
для создания пустого объекта JSON я обычно использую:
приведение null к объекту работает, но есть ли другой предпочтительный способ и/или какие-либо проблемы с этим решением?
6 ответов:
ваше решение может работать..
в документации указано, что (object) null приведет к пустому объекту, поэтому некоторые могут сказать, что ваш код действителен и что это метод для использования.
если значение любого другого типа преобразуется в объект, создается новый экземпляр встроенного класса stdClass создается. Если значение равно NULL, то новый экземпляр будет пустой.
.. но, постарайтесь сохранить его в безопасности!
хотя вы никогда не знаете, когда/если выше будут меняться, так что если вы хотите быть на 100% уверены, что вы всегда будете в конечном итоге с помощью <> в закодированных данных, вы можете использовать Хак, таких как:
хотя это утомительно и некрасиво, я предполагаю / надеюсь, что json_encode/json_decode совместим с одним и другим и всегда будет оценивать следующее правда:
Рекомендуемый метод
если вы используете объекты в качестве динамических словарей (и я думаю, что вы делаете), то я думаю, что вы хотите использовать ArrayObject.
он отображается в словарь JSON, даже когда он пуст. это здорово, если вам нужно различать списки (массивы) и словари (ассоциативные массивы):
вы также можете легко манипулировать им (как и с ассоциативным массивом), и он будет правильно отображаться в a словарь:
Если вам нужно, чтобы это было 100% совместимо и способы, вы также можете обернуть json_decode Так что он возвращает ArrayObjects вместо stdClass объекты (вам нужно будет пройти по дереву результатов и рекурсивно заменить все объекты, что является довольно простой задачей).
Ну json_encode() просто возвращает строку из массива PHP / object / etc. Вы можете достичь того же эффекта гораздо более эффективно делать:
нет смысла в использовании функции для этого.
обновление Согласно вашим обновлениям комментариев, Вы можете попробовать:
хотя я не уверен, что это лучше, чем то, что ты делаешь.
для создания пустого объекта в JSON с PHP я использовал
что необходимо, потому что потом я должен сделать это
Как определить пустой объект в PHP
с новым массивом я делаю это:
Есть ли аналогичный синтаксис для объекта
ОТВЕТЫ
Ответ 1
При сканировании или массиве Объект, вы получаете экземпляр StdClass. Вы можете использовать stdClass когда вам нужен общий объект экземпляр.
Ответ 2
Стандартный способ создания «пустого» объекта:
Но, с PHP >= 5.4, я лично предпочитаю использовать:
Это короче, и я лично считаю его более ясным, потому что stdClass может вводить в заблуждение начинающих программистов (т.е. «Эй, я хочу объект, а не класс!». ).
См. руководство по PHP (здесь):
stdClass. Создается при помощи метода typecasting для объекта.
Если объект преобразуется в объект, он не изменяется. Если значение любого другого типа преобразуется в объект, создается новый экземпляр встроенного класса stdClass.
Однако помните, что empty ($ oVal) возвращает false, поскольку @PaulP сказал:
Объекты без свойств больше не считаются пустыми.
Относительно вашего примера, если вы пишете:
PHP создает следующее Предупреждение, неявно создающее свойство key1 (сам объект)
Предупреждение: создание объекта по умолчанию из пустого значения
Это может быть проблемой, если ваша конфигурация (см. уровень отчетности об ошибках) показывает это предупреждение в браузере. Это еще одна тема, но быстрый и грязный подход может использовать оператор управления ошибкой (@), чтобы игнорировать предупреждение:
Ответ 3
Я хочу указать, что в PHP нет такой вещи, как пустой объект в смысле:
С другой стороны, пустой массив пуст в обоих случаях
Цитата из функции changelog empty
Объекты без свойств больше не считаются пустыми.
Ответ 4
php.net сказал, что это лучше всего:
Ответ 5
Мне нравится, как легко создавать объекты анонимного типа в JavaScript:
Поэтому я всегда стараюсь писать такие объекты на PHP, как javascript:
Но поскольку это в основном массив, вы не можете делать такие вещи, как назначение анонимных функций для свойства, подобного js:
Ну, вы можете это сделать, но IMO не практично/чисто:
Кроме того, используя этот синтаксис, вы можете найти забавные сюрпризы, но отлично работает в большинстве случаев.
Ответ 6
В дополнение к зомбату ответ, если вы продолжаете забывать stdClass
Теперь вы можете сделать:
Ответ 7
для доступа к данным в stdClass аналогичным образом с асоциальным массивом просто используйте синтаксис <$ var>.
Ответ 8
Вы можете использовать new stdClass() (который рекомендуется):
Или вы можете преобразовать пустой массив в объект, который создает новый пустой экземпляр встроенного класса stdClass:
Или вы можете преобразовать значение null в объект, который создает новый пустой экземпляр встроенного класса stdClass:
Ответ 9
Вы также можете попробовать этот путь.
Ответ 10
Как указывали другие, вы можете использовать stdClass. Однако я думаю, что он чист без(), например:
Однако на основе вопроса кажется, что вы действительно хотите, чтобы иметь возможность добавлять свойства к объекту «на лету». Вам не нужно использовать stdClass для этого, хотя вы можете. Действительно, вы можете использовать любой класс. Просто создайте экземпляр объекта любого класса и начните устанавливать свойства. Мне нравится создавать свой собственный класс, чье имя просто o с некоторыми базовыми расширенными функциональными возможностями, которые я люблю использовать в этих случаях, и хорошо для распространения из других классов. В основном это мой собственный базовый класс объектов. Мне также нравится иметь функцию, просто называемую o(). Например:
Это отличный старт для базового «языка» для создания других языковых слоев, когда верхний слой записывается в полные внутренние DSL. Это похоже на стиль разработки lisp, а PHP поддерживает его лучше, чем большинство людей понимают. Я понимаю, что это немного касательно вопроса, но вопрос касается того, что я считаю основой для полного использования возможностей PHP.
Ответ 11
Если вы хотите создать объект (например, в javascript) с динамическими свойствами, не получая предупреждение о свойстве undefined.
Ответ 12
Мы можем просто создать пустой объект с помощью этого метода:
Я знаю, что это старый вопрос, но кажется, что некоторые люди забывают о конструкторах.
Ответ 13
Если вы не хотите этого делать:
Вы можете использовать одно из следующих действий:
PHP >= 5.4
Ответ 14
Используйте для него пары значений общего класса и карты.
Или выделите массив в объект
Ответ 15
Вот пример с итерацией:
Ответ 16
У вас есть эта плохая, но полезная техника: