Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

วิธี chain methods ใน PHP


Mutator methods ใช้ chain methods โดยเมธอดเหล่านี้คืนอ็อบเจกต์เดิม และเมธอดอื่นๆ สามารถเรียกบนอ็อบเจกต์ที่คืนมาโดย mutator functions

ตัวอย่าง

ตัวอย่างง่ายด้านล่าง:

<?php class sample_class {    private $str;    function __construct() {       $this->str = "";    }    function addA() {       $this->str .= "am";       return $this;    }    function addB() {       $this->str .= "_bn";       return $this;    }    function getStr() {       return $this->str;    } } $new_object = new sample_class(); echo $new_object->addA()->addB()->getStr();

ผลลัพธ์

จะได้ผลลัพธ์ดังนี้:

am_bn