Pouvez-vous enchaîner des méthodes sur un nouvel objet en PHP ?

Susan Sarandon
Libérer: 2024-10-18 14:59:03
original
590 Les gens l'ont consulté

Can You Chain Methods on a New Object in PHP?

Chaining Methods on a Newly Created Object

In PHP, it's not immediately clear if it's possible to chain methods on a newly created object. This question explores this question, asking if there's a way to achieve the following syntax:

<code class="php">class Foo {
    public function xyz() { ... return $this; }
}

$my_foo = new Foo()-&gt;xyz();</code>
Copier après la connexion

In PHP 5.4+, the parser has been modified to allow chaining directly after instantiation:

<code class="php">(new Foo())-&gt;xyz();</code>
Copier après la connexion

Simply wrap the instantiation in parentheses and proceed with chaining.

However, in PHP 5.3 and earlier, chaining directly after instantiation is not possible due to limitations in the syntax. To workaround this, one can use a static instantiation method:

<code class="php">class Foo
{
    public function xyz()
    {
        echo "Called","\n";
        return $this;
    }

    static public function instantiate()
    {
        return new self();
    }
}


$a = Foo::instantiate()-&gt;xyz();</code>
Copier après la connexion

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!