Bagaimana untuk Menyelesaikan Ralat Apabila Melepasi Susunan Objek sebagai Argumen Fungsi?

DDD
Lepaskan: 2024-10-18 06:53:30
asal
237 orang telah melayarinya

How to Resolve Errors When Passing an Array of Objects as Function Arguments?

Type Hinting: Array of Objects

When passing an array of objects as an argument to a function, you may encounter an error if the argument type is not specified. For example, consider the following code:

<code class="php">class Foo {}

function getFoo(Foo $f) {}</code>
Salin selepas log masuk

Attempting to pass an array of Foo objects to getFoo will result in a fatal error:

<code class="php">Argument 1 passed to getFoo() must be an instance of Foo, array given</code>
Salin selepas log masuk

To overcome this issue, you can specify the argument type as an array of the desired object type using a custom class. For instance, an ArrayOfFoo class can be defined as follows:

<code class="php">class ArrayOfFoo extends \ArrayObject {
    public function offsetSet($key, $val) {
        if ($val instanceof Foo) {
            return parent::offsetSet($key, $val);
        }
        throw new \InvalidArgumentException('Value must be a Foo');
    }
}</code>
Salin selepas log masuk

This class ensures that only Foo objects can be assigned to its elements. The getFoo function can then be updated to accept an ArrayOfFoo argument:

<code class="php">function getFoo(ArrayOfFoo $foos) {
    foreach ($foos as $foo) {
        // ...
    }
}</code>
Salin selepas log masuk

Now, passing an array of Foo objects to getFoo will work as expected.

Alternatively, the Haldayne library can be used to simplify the process:

<code class="php">class ArrayOfFoo extends \Haldayne\Boost\MapOfObjects {
    protected function allowed($value) { return $value instanceof Foo; }
}</code>
Salin selepas log masuk

This class provides built-in checks to ensure that only Foo objects are allowed in the array.

Atas ialah kandungan terperinci Bagaimana untuk Menyelesaikan Ralat Apabila Melepasi Susunan Objek sebagai Argumen Fungsi?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!