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

สร้าง Object เรียก Method ทันทีในบรรทัดเดียว (PHP 5.4+)

ตั้งแต่ PHP 5.4 สามารถสร้าง Object (Instantiate) และเรียก Method ทันทีในบรรทัดเดียวได้ เรียกว่า Class Member Access on Instantiation

Syntax พื้นฐาน

(new ClassName())->methodName();

// หรือมี Constructor Arguments
(new ClassName($arg1, $arg2))->methodName();

ตัวอย่างสมบูรณ์

class Calculator {
    private $value;
    
    public function __construct($initialValue = 0) {
        $this->value = $initialValue;
    }
    
    public function add($num) {
        $this->value += $num;
        return $this; // Return $this เพื่อ Method Chaining
    }
    
    public function multiply($num) {
        $this->value *= $num;
        return $this;
    }
    
    public function getResult() {
        return $this->value;
    }
}

// ใช้งาน: Instantiation + Method Chaining ในบรรทัดเดียว
$result = (new Calculator(10))
    ->add(5)
    ->multiply(2)
    ->getResult();

echo $result; // 30

ตัวอย่างจากคำถามเดิม

class TestClass {
    protected $_var;
    
    public function __construct($param) {
        $this->_var = $param;
    }
    
    public function myMethod() {
        return $this->_var * 2;
    }
}

// ฟังก์ชัน Factory (Optional)
function TestClass($param) {
    return new TestClass($param);
}

// เรียกในบรรทัดเดียว
$a = TestClass(10)->myMethod();
var_dump($a); // int(20)

// หรือโดยตรง
$b = (new TestClass(10))->myMethod();
var_dump($b); // int(20)

กรณีใช้งานจริง (Real-world Use Cases)

1. Fluent Interface / Builder Pattern

class QueryBuilder {
    private $query = [];
    
    public function select($fields) {
        $this->query['select'] = $fields;
        return $this;
    }
    
    public function from($table) {
        $this->query['from'] = $table;
        return $this;
    }
    
    public function where($column, $operator, $value) {
        $this->query['where'][] = [$column, $operator, $value];
        return $this;
    }
    
    public function get() {
        // Build & Execute SQL...
        return $this->query; // Demo
    }
}

// ใช้งาน
$sql = (new QueryBuilder())
    ->select(['id', 'name', 'email'])
    ->from('users')
    ->where('status', '=', 'active')
    ->where('created_at', '>', '2024-01-01')
    ->get();

2. Dependency Injection Container (Simple)

class Container {
    private $services = [];
    
    public function set($key, $concrete) {
        $this->services[$key] = $concrete;
        return $this;
    }
    
    public function get($key) {
        $concrete = $this->services[$key];
        return is_callable($concrete) ? $concrete($this) : $concrete;
    }
}

$container = (new Container())
    ->set('db', fn($c) => new PDO('mysql:host=localhost;dbname=test', 'user', 'pass'))
    ->set('userRepo', fn($c) => new UserRepository($c->get('db')));

3. Event Dispatcher / Middleware Chain

class Request {
    public $data = [];
}

class Middleware {
    public function handle(Request $request, callable $next) {
        // Before
        $response = $next($request);
        // After
        return $response;
    }
}

// Chain ในบรรทัดเดียว
$response = (new Middleware())->handle(
    new Request(),
    fn($req) => (new AnotherMiddleware())->handle($req, fn($r) => 'Final Response')
);

ข้อจำกัด

  • ต้องใช้ PHP 5.4+ (ปัจจุบัน PHP 8.x เป็นมาตรฐาน)
  • Constructor ต้องเป็น public
  • Method ต้อง Return $this (สำหรับ Chaining) หรือค่าที่ต้องการ
  • Debug ยากกว่า (Stack Trace ไม่ชัดเจน) - ควรแยกบรรทัดถ้า Logic ซับซ้อน