Меню

Ошибка creating default object from empty value

I see this error only after upgrading my PHP environment to PHP 5.4 and beyond. The error points to this line of code:

Error:

Creating default object from empty value

Code:

$res->success = false;

Do I first need to declare my $res object?

Michael Berkowski's user avatar

asked Jan 17, 2012 at 19:43

Paul's user avatar

3

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;

answered Jan 17, 2012 at 19:45

Michael Berkowski's user avatar

Michael BerkowskiMichael Berkowski

265k46 gold badges441 silver badges385 bronze badges

15

This message has been E_STRICT for PHP <= 5.3. Since PHP 5.4, it was unluckilly changed to E_WARNING. Since E_WARNING messages are useful, you don’t want to disable them completely.

To get rid of this warning, you must use this code:

if (!isset($res)) 
    $res = new stdClass();

$res->success = false;

This is fully equivalent replacement. It assures exactly the same thing which PHP is silently doing — unfortunatelly with warning now — implicit object creation. You should always check if the object already exists, unless you are absolutely sure that it doesn’t. The code provided by Michael is no good in general, because in some contexts the object might sometimes be already defined at the same place in code, depending on circumstances.

answered Jan 8, 2014 at 20:10

Tomas's user avatar

TomasTomas

56.5k48 gold badges232 silver badges368 bronze badges

2

Simply,

    $res = (object)array("success"=>false); // $res->success = bool(false);

Or you could instantiate classes with:

    $res = (object)array(); // object(stdClass) -> recommended

    $res = (object)[];      // object(stdClass) -> works too

    $res = new stdClass(); // object(stdClass) -> old method

and fill values with:

    $res->success = !!0;     // bool(false)

    $res->success = false;   // bool(false)

    $res->success = (bool)0; // bool(false)

More infos:
https://www.php.net/manual/en/language.types.object.php#language.types.object.casting

answered Jan 17, 2016 at 18:25

pirs's user avatar

pirspirs

2,3202 gold badges17 silver badges25 bronze badges

4

If you put «@» character begin of the line then PHP doesn’t show any warning/notice for this line. For example:

$unknownVar[$someStringVariable]->totalcall = 10; // shows a warning message that contains: Creating default object from empty value

For preventing this warning for this line you must put «@» character begin of the line like this:

@$unknownVar[$someStringVariable]->totalcall += 10; // no problem. created a stdClass object that name is $unknownVar[$someStringVariable] and created a properti that name is totalcall, and it's default value is 0.
$unknownVar[$someStringVariable]->totalcall += 10; // you don't need to @ character anymore.
echo $unknownVar[$someStringVariable]->totalcall; // 20

I’m using this trick when developing. I don’t like disable all warning messages becouse if you don’t handle warnings correctly then they will become a big error in future.

answered Jul 4, 2017 at 12:59

kodmanyagha's user avatar

kodmanyaghakodmanyagha

89311 silver badges20 bronze badges

4

Try this if you have array and add objects to it.

$product_details = array();

foreach ($products_in_store as $key => $objects) {
  $product_details[$key] = new stdClass(); //the magic
  $product_details[$key]->product_id = $objects->id; 
   //see new object member created on the fly without warning.
}

This sends ARRAY of Objects for later use~!

answered Jun 12, 2015 at 9:00

Nickromancer's user avatar

NickromancerNickromancer

7,4637 gold badges55 silver badges75 bronze badges

1

answered Nov 30, 2020 at 13:46

bancer's user avatar

bancerbancer

7,3857 gold badges37 silver badges58 bronze badges

  1. First think you should create object
    $res = new stdClass();

  2. then assign object with key and value thay
    $res->success = false;

answered Apr 28, 2020 at 4:25

Sukron Ma'mun's user avatar

1

Try this:

ini_set('error_reporting', E_STRICT);

answered Sep 5, 2013 at 8:54

Irfan's user avatar

IrfanIrfan

4,75212 gold badges50 silver badges62 bronze badges

5

I had similar problem and this seem to solve the problem. You just need to initialize the $res object to a class . Suppose here the class name is test.

class test
{
   //You can keep the class empty or declare your success variable here
}
$res = new test();
$res->success = false;

answered Aug 6, 2018 at 8:06

Kevin Stephen Biswas's user avatar

Starting from PHP 7 you can use a null coalescing operator to create a object when the variable is null.

$res = $res ?? new stdClass();
$res->success = false;

Florian Rival's user avatar

answered Apr 12, 2022 at 13:30

Lost user's user avatar

A simple way to get this error is to type (a) below, meaning to type (b)

(a) $this->my->variable

(b) $this->my_variable

Trivial, but very easily overlooked and hard to spot if you are not looking for it.

mega6382's user avatar

mega6382

9,03117 gold badges48 silver badges69 bronze badges

answered Mar 15, 2016 at 9:01

Tannin's user avatar

1

You may need to check if variable declared and has correct type.

if (!isset($res) || !is_object($res)) {
    $res = new stdClass();
    // With php7 you also can create an object in several ways.
    // Object that implements some interface.
    $res = new class implements MyInterface {};
    // Object that extends some object.
    $res = new class extends MyClass {};
} 

$res->success = true;

See PHP anonymous classes.

answered Nov 15, 2017 at 20:08

Anton Pelykh's user avatar

Anton PelykhAnton Pelykh

2,1501 gold badge18 silver badges21 bronze badges

Try using:

$user = (object) null;

answered Nov 8, 2018 at 22:10

Fischer Tirado's user avatar

1

I had a similar problem while trying to add a variable to an object returned from an API. I was iterating through the data with a foreach loop.

foreach ( $results as $data ) {
    $data->direction = 0;
}

This threw the «Creating default object from empty value» Exception in Laravel.

I fixed it with a very small change.

foreach ( $results as &$data ) {
    $data->direction = 0;
}

By simply making $data a reference.

I hope that helps somebody a it was annoying the hell out of me!

answered Mar 14, 2019 at 4:56

Andy's user avatar

AndyAndy

3034 silver badges10 bronze badges

no you do not .. it will create it when you add the success value to the object.the default class is inherited if you do not specify one.

answered Jan 17, 2012 at 19:46

Silvertiger's user avatar

SilvertigerSilvertiger

1,6802 gold badges19 silver badges32 bronze badges

2

This problem is caused because your are assigning to an instance of object which is not initiated. For eg:

Your case:

$user->email = 'exy@gmail.com';

Solution:

$user = new User;
$user->email = 'exy@gmail.com';

answered Jun 8, 2014 at 4:46

Bastin Robin's user avatar

4

This is a warning which I faced in PHP 7, the easy fix to this is by initializing the variable before using it

$myObj=new stdClass();

Once you have intialized it then you can use it for objects

 $myObj->mesg ="Welcome back - ".$c_user;

answered Nov 4, 2019 at 14:52

Ayan Bhattacharjee's user avatar

I put the following at the top of the faulting PHP file and the error was no longer display:

error_reporting(E_ERROR | E_PARSE);

answered Feb 6, 2016 at 14:59

Doug's user avatar

DougDoug

4,99610 gold badges31 silver badges42 bronze badges

0

  1. Create a stdClass() Object in PHP
  2. Typecast Array Into Object in PHP
  3. Create Object From Anonymous Class in PHP

Create Default Object From Empty Value in PHP

We will introduce some methods for creating objects in PHP and solving the error creating default object from empty value.

Create a stdClass() Object in PHP

When we try to assign properties of an object without initializing an object, an error will be thrown. The error will say creating default object from empty value. The error also depends upon the configuration in the php.ini file. When the error is suppressed in the configuration, then such script will not throw the error. It is not better to change the configuration file to suppress the error to get rid of it. Instead, we can create a stdClass() object to get rid of the error. When we declare a variable as an object of the stdClass() in the global namespace, we can dynamically assign properties to the objects.

For example, create a variable $obj and set it to NULL. Then, set the success property to false with the $obj object. In this instance, an error will be thrown, as shown in the output section. It is because $obj has not been initialized as an object.

Example Code:

$obj = NULL;
$obj->success = true;

Output:

Warning: Creating default object from empty value

To eliminate the error, first, assign the $obj variable with the instance of stdClass(). Next, set the success property to true with the $obj. Then, print the $obj object using the print_r() function. It is even better to use the isset() function to check if $obj exists already. We can see the information about $obj in the output section. Thus, we can eliminate the error by creating an object of stdClass().

Example Code:

$obj = new stdClass();
$obj->success =true;
print_r($obj);

Output:

stdClass Object ( [success] => 1 ) 

Typecast Array Into Object in PHP

We can typecast an array to an object using the object keyword before the array. In this way, the object can be created. Then, we can assign the properties to the object. Since we already initialized the object, no error will be thrown while assigning properties of the object. This method also creates an object of the stdClass() class.

For example, create a variable $obj and assign it to the array() function. Then, write the object keyword in parenthesis before array(). The array has been converted into an object. Then, assign the true value to the success property with the $obj. Finally, print the object with the print_r() function. In this way, we can create an object typecasting an array and get rid of the error.

Example Code:

$obj = (object)array();
$obj->success =true;
print_r($obj);

Output:

stdClass Object ( [success] => 1 ) 

Create Object From Anonymous Class in PHP

We can create an object from an anonymous class in PHP and assign properties to it. We can use the new class keyword to create an anonymous class. We can set the value of the properties as in the generic class. Since the property will have a class, and we can access it with an object, no error will be thrown.

For example, create an object $obj assign an anonymous class using the new class keyword to the object. Then create a public property $success and set the value to true. Outside, the class, print the object with the print_r() function. In this way, we can create an object from an anonymous class in PHP and prevent the error.

Example Code:

$obj = new class {
 public $success = true;
};
print_r($obj);

Output:

class@anonymous Object ( [success] => 1 ) 
Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php(170) : eval()'d code on line 1

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 268

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php(170) : eval()'d code on line 1

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 268

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php(170) : eval()'d code on line 1

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php(170) : eval()'d code on line 1

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php(170) : eval()'d code on line 1

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php(170) : eval()'d code on line 1

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php(170) : eval()'d code on line 1

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php(170) : eval()'d code on line 1

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php(170) : eval()'d code on line 1

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php(170) : eval()'d code on line 1

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php(170) : eval()'d code on line 1

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php(170) : eval()'d code on line 1

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php(170) : eval()'d code on line 1

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php(170) : eval()'d code on line 1

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php(170) : eval()'d code on line 1

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php(170) : eval()'d code on line 1

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 268

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 268

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 268

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 268

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 184

Warning: Creating default object from empty value in /opt/lampp/htdocs/j1/libraries/joomla/updater/update.php on line 268
Обнаружено обновление Joomla!
Установленная версия Joomla! 2.5.8
Последняя версия Joomla! 2.5.9
Пакет обновления (URL) http://joomlacode.org/gf/download/frsrelease/17967/78436/Joomla_2.5.x_to_2.5.9-Stable-Patch_Package.zip
Способ установки
  Установить обновление

Работая с одним из проектов заказчика столкнулся с ошибкой добавления постов. Они просто не добавлялись, залез в базу там висят несколько постов без номеров и перекрывают возможность добавлять новые. Ошибка

Warning: Creating default object from empty value in /public_html/wpadmin/includes/post.php on line 716

Начал ковырять и вот как получилось исправить данную проблему

  1. Сделал резервную копию с помощью опции Инструменты> Экспорт
  2. Зашел в файл wp-config и изменил имя префикса таблицы на совершенно новое. $ table_prefix = ‘изменить это имя’;
  3. Зашел на mysite.com/wp-admin и ввел информацию в установку WordPress.
  4. Пошел в Инструменты> Импорт> WordPress. Включены вложения.
  5. На то, чтобы все содержимое появилось снова, потребовалось около получаса, но, похоже, сейчас он работает правильно.

Ошибка связана с отключением Auto_increment для идентификатора столбца таблицы wp_posts . Вы можете включить опцию Auto Increment в PhpMyAdmin .

wp_posts -> Структура -> Изменить параметр для идентификатора столбца -> Отметьте параметр AUTO_INCREMENT -> Сохранить.

Вы можете выполнить следующий запрос в базе данных:

ALTER TABLE wp_postsCHANGE ID IDBIGINT (20) UNSIGNED NOT NULL AUTO_INCREMENT;

Вам также может потребоваться включить Автоинкремент для таблицы wp_postmeta .

Ошибка в бэкенде в ленте событий

Исправлено

1

Сайт 4showdog.com, соответственно, страница http://4showdog.com/webasyst

После обновления до PHP 7.4 в ленте событий в самом начале появляются ошибки:

Warning: Creating default object from empty value in /home/virtwww/w_4showdog2_65443d60/http/wa-cache/apps/webasyst/templates/compiled/webasyst_ru_RU/e4/b7/be/e4b7becad979d5eba98507ba249586b6cb6e314c.file.DashboardActivity.html.php on line 34 Warning: Creating default object from empty value in /home/virtwww/w_4showdog2_65443d60/http/wa-cache/apps/webasyst/templates/compiled/webasyst_ru_RU/e4/b7/be/e4b7becad979d5eba98507ba249586b6cb6e314c.file.DashboardActivity.html.php on line 34 Warning: Creating default object from empty value in /home/virtwww/w_4showdog2_65443d60/http/wa-cache/apps/webasyst/templates/compiled/webasyst_ru_RU/e4/b7/be/e4b7becad979d5eba98507ba249586b6cb6e314c.file.DashboardActivity.html.php on line 34 Warning: Creating default object from empty value in /home/virtwww/w_4showdog2_65443d60/http/wa-cache/apps/webasyst/templates/compiled/webasyst_ru_RU/e4/b7/be/e4b7becad979d5eba98507ba249586b6cb6e314c.file.DashboardActivity.html.php on line 34 Warning: Creating default object from empty value in /home/virtwww/w_4showdog2_65443d60/http/wa-cache/apps/webasyst/templates/compiled/webasyst_ru_RU/e4/b7/be/e4b7becad979d5eba98507ba249586b6cb6e314c.file.DashboardActivity.html.php on line 34 Warning: Creating default object from empty value in /home/virtwww/w_4showdog2_65443d60/http/wa-cache/apps/webasyst/templates/compiled/webasyst_ru_RU/7e/b9/ac/7eb9ac0303954a0e230b101d219699682588a34c.file.BackendDashboard.html.php on line 273

Видно, что ошибка в строке 273 файла BackendDashboard.html.php выходит один раз, а следующая за ней постепенно забивает всю ленту на экране

7 комментариев

  • популярные
  • новые


  • +1

    Системные требования

    Веб-сервер

    Apache + mod_php, Nginx, Lighttpd или любой другой веб-сервер + FastCGI.

    PHP

    Версия 5.6—7.2



    • +1

      Я перешел на PHP 7.4 потому что в одном из последних обновлений говорилось, что сделаны исправления для работы именно с этой версией. Я правильно понимаю, что PHP 7.4 пока не поддерживается и надо откатиться на PHP 7.2?



      • +1

        полноценной поддержки не заявлено



        • +1

          Теперь понятно, подождем. В принципе, эта ошибка не принципиальна, а других в работе сайта на PHP 7.4.4 я пока не нашел, поэтому ничего трогать не буду.



        • +1

          А папку cache чистили после обновления?



          • +1

            Мы выпустили обновление фреймворка Webasyst для улучшения поддержки последних версий PHP. Обновление можно установить в «Инсталлере».

            Проверьте, пожалуйста. Сообщите нам, если проблема сохранилась.

            Добавить комментарий

            danyasher

            Сообщения: 2
            Зарегистрирован: 2017.01.30, 19:26

            Creating default object from empty value

            Всем привет, подскажите новичку как победить ошибку.
            Ни как не разберусь. Как понимаю не создана переменная, но если их создать то ругается на одинаковые переменные php 7.1 как можно обойти?

            Код: Выделить всё

            if (!empty(Yii::$app->session['add_photos'])) {
             
                            $DateTime = new DateTime('NOW');
                            $DateTimeFormat = $DateTime->format('Y-m-d H:i:s');
                            $Orders->created = $DateTimeFormat;
                            $Orders->user_id = Yii::$app->session['user_id'];
                            $Orders->status = 'draft';
                            $Orders->price_id = Yii::$app->session['id_prices'];
                            if ($Orders->save()) {
                                $array_to_orders = array_merge($new_array, $fileupload_array);
                                foreach ($array_to_orders as &$ato) {
                                    $count = $ato[1];

            Onotole

            Сообщения: 1808
            Зарегистрирован: 2012.12.24, 12:49

            danyasher

            Сообщения: 2
            Зарегистрирован: 2017.01.30, 19:26

            Re: Creating default object from empty value

            Сообщение

            danyasher » 2017.01.31, 00:50

            Код: Выделить всё

            PHP Warning – yiibaseErrorException
            
            Creating default object from empty value
            1. /frontend/controllers/EditPhotosController.php at line 115
                                }
             
                            }
                        }
             
                        if (!empty(Yii::$app->session['add_photos'])) {
             
                            $DateTime = new DateTime('NOW');
                            $DateTimeFormat = $DateTime->format('Y-m-d H:i:s');
                            $Orders->created = $DateTimeFormat;
                            $Orders->user_id = Yii::$app->session['user_id'];
                            $Orders->status = 'draft';
                            $Orders->price_id = Yii::$app->session['id_prices'];
                            if ($Orders->save()) {
                                $array_to_orders = array_merge($new_array, $fileupload_array);
                                foreach ($array_to_orders as &$ato) {
                                    $count = $ato[1];

            Onotole

            Сообщения: 1808
            Зарегистрирован: 2012.12.24, 12:49

            Сегодня расковыривал один компонент для Joomla 1.5 и в процессе нашелся такой вот забавный баг. При построении списка создавался массив, который отдавал в логи ошибку при каждой итерации:

            Warning: Creating default object from empty value in /srv/vhosts/…/xxx.php on line 200

            Ларчик просто открывался. Эта ошибка справедлива для PHP >=5.4, для более ранних версий все будет хорошо.

            Выяснилось, что в строке 200 было это:

            $lists[$i]->value = $row->product_available_date;

            Естественно, вместо $row->product_available_date может быть что угодно. Чтобы это дело пофиксить, определяем это все дело в качестве класса:

            $lists[$i] = new stdClass();

            То есть, в конечном итоге получается вот такое:

            $lists[$i] = new stdClass();
            $lists[$i]->value = $row->product_available_date;

            Стоит учесть, что конструкции:

            $lists[$i] = NULL;
            $lists[$i]->value = $row->product_available_date;

            или, например,

            $lists[$i] = 123;
            $lists[$i]->value = $row->product_available_date;

            или

            $lists[$i] = '';
            $lists[$i]->value = $row->product_available_date;

            будут не верны.

            То есть, создавая объект в PHP >=5.4, нужно объявить его как stdClass().

            0 0 голоса
            Рейтинг статьи
            Подписаться
            Уведомить о
            guest

            0 комментариев
            Старые
            Новые Популярные
            Межтекстовые Отзывы
            Посмотреть все комментарии

            А вот еще интересные материалы:

          • Яшка сломя голову остановился исправьте ошибки
          • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
          • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
          • Ошибка csc 7200020 на алиэкспресс
          • Ошибка createservice failed with 5 easy anti cheat