0

私はあちこちでこれに遭遇し、常に回避してきましたが、知っておく必要があります。
これは配列、オブジェクト、または??? (これを 経由で取得したとしましょうvar_export($co)

stdClass::__set_state(array(
   'name' => 'Acme Anvil Corp.',
))

最も重要なのは、どうすれば価値を付加できるか?
のような値を追加したいとしましょう$co->owner = 'Wiley Coyote'。それは常に警告をスローします。

どのように?
何?

好奇心は私を殺すだけです:)

[編集]
明確にするために、私の質問の根本は「警告をトリガーせずにオブジェクトに変数を追加するにはどうすればよいですか?」だと思います。

これが私がいつも受け取る警告です:

PHP エラーが発生しました
重大度: 警告
メッセージ: 非オブジェクトのプロパティを割り当てようとしています

And a var_dump($co)yields: (関連する場合、現在はループで実行されます)

object(stdClass)#185 (1) {
  ["name"]=>
  string(16) "Acme Anvil Corp."
}

[/編集]

4

3 に答える 3

1

$coタイプのオブジェクトですstdClass。警告なしに1つ作成し、必要な数のプロパティを追加できます。

$obj = new stdClass();
$obj->prop1 = 'val1';
$obj->prop2 = 3.14;

直面している警告はおそらくCreating default object from null value、初期化されていない変数にプロパティを割り当てようとしていることを意味します。

オブジェクトにはメソッドがないため、var_exportforオブジェクトによって生成されたコードを実行しようとしないでください。stdClass__setState

于 2012-10-31T22:42:50.240 に答える
0

あなたのエラーについてはよくわかりませんが、stdClass クラスは PHP の組み込みクラスのデフォルトです。

基本的に空のオブジェクトです

プロパティを設定できるはずです$class->foo = 'bar'

stdClass について話しているのではなく、var_export で配列を取得しているという事実がある場合、それは単に内部オブジェクトの状態の表現です。

class Foo
{
    private $bar = 'baz';
}

$foo = new Foo();

var_export($foo);

次のような出力が得られるはずです

Foo::__set_state(array(
   'bar' => 'baz',
))

表示される警告は、プロパティが保護/非公開であることが原因である可能性があります。

var_dump()通常、内部オブジェクトのアクセス修飾子については、var_export()

表示される警告と質問の内容を明確にしていただけますか。質問内容に関連するように回答を編集します

于 2012-10-31T22:40:41.033 に答える
0

var_export() prints executable PHP code able to recreate the variable exported.

When encountering objects, they are always exported as a call to their static magic method __set_state(). Compared to other magic methods, this method does not really have much magic in it besides the fact that var_export guarantees to create static calls with this method, so it is simply just the agreed upon name for such a method.

The __set_state() method of a class should return an instance of the object with all exported properties set to the values given as the array parameter.

Example:

class Foo {
  public $bar;

  public static function __set_state($params) {
    $obj = new Foo;
    foreach ($params as $key => $value) {
      $obj->$key = $value;
    }
    return $obj;
  }
}

$foo = new Foo;
$foo->bar = "Hello World";

var_export($foo);

This prints something like:

Foo::__set_state(array('bar' => 'Hello World'));

If you execute this and save it to a variable again:

$x = Foo::__set_state(array('bar' => 'Hello World'));

it will recreate the object with all given properties set.

It does not work with stdClass objects, because they don't have a __set_state() method.

See http://de3.php.net/manual/en/language.oop5.magic.php#object.set-state for more info.

Update:

This code does not trigger any warnings:

ini_set('display_errors', 1);
error_reporting(E_ALL | E_STRICT);

$co = new stdClass();

$co->name = 'Acme Anvil Corp.';

var_export($co);

$co->owner = 'Wiley Coyote';
于 2012-11-01T00:47:01.733 に答える