0

次のような変数を表示しようとしているときにエラーを受け取りました。

echo "id is $url->model->id";

問題は、echo がこのように表示される単純な変数 ($id や $obj->id など) のみを好むことです。

class url {
    public function  __construct($url_path) {
        $this->model = new url_model($url_path);
    }
}

class url_model {
    public function  __construct($url_path) {
        $this->id = 1;
    }
}

その後

$url = new url();
echo "id is $url->model->id"; // does not work

$t = $url->model->id;
echo "id is $t";  //works

$t = $url->model;
echo "id is $t->id";  //works

echo "id is {$url->model->id}"; //works. This is the same syntax used to display array elements in php manual.

//php manual example for arrays
echo "this is {$baz['value']}";

なぜ機能するのかわかりません。構文を推測しただけです。

echo "..."PHPマニュアルでは、オブジェクトの使用方法については述べていません。また、いくつかの奇妙な動作があります。単純な変数でエコーし、動作します。オブジェクトの単純なプロパティでエコーが機能します。別のオブジェクト内にあるオブジェクトの単純なプロパティでのエコーは機能しません。

これecho "id is {$url->model->id}";は正しい方法ですか?もっと簡単な方法はありますか?

4

2 に答える 2

1

アップデート :

たぶん私は間違っています、エコーする$url->model$url->model->id、それを文字列に変換して返そうとするだけなので、それを行うことができますが__toString、モデルに関数が必要です

私は自分のポイントを明確にするために例を挙げました:

class url {
    public function  __construct($url_path) {
        $this->model = new url_model($url_path);
    }
}

class url_model {
    public function  __construct($url_path) {
        $this->id = 1;
    }

    public function __toString()
    {
        return (string) $this->id ; 
    }
}

$url = new url("1");
echo "id is $url->model->id"; // it will  convert $url->model to "1" , so the string will be 1->id
echo "id is $url->model"; // this will  work now too 
$t = $url->model->id;
echo "id is $t";  //works
$t = $url->model;
echo "id is $t->id";  //works
echo "id is {$url->model->id}"; //works. This is the same syntax used to display array elements in php manual

しかし、私は何echo "this is {$baz['value']}";のためにあるのかわからない?????

マジック メソッドの詳細については、 __toStringを確認してください

しかし、私はむしろ固執したいと思い{$url->model->id}ます。

于 2012-06-14T09:48:02.260 に答える