3v4l.org

run code in 500+ PHP versions simultaneously
<?php namespace StockExample; interface Order { public function execute(); } class StockBuy { public function __invoke() { echo "You want to buy stocks via __invoke()" . PHP_EOL; } } class StockSell { public function __invoke() { echo "You want to sell stocks __invoke()" . PHP_EOL; } } class MyCommand implements Order { private $action; public function __construct(callable $action) { $this->action = $action; } public function execute() { // Option 1) use call_user_function call_user_func($this->action); // Option 2) define it as a variable and call it by adding `()` //$action = $this->action; //$action(); } } // example with a callable object $bsc = new MyCommand(new StockBuy()); $ssc = new MyCommand(new StockSell()); $bsc->execute(); $ssc->execute();
Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.18, 8.5.0 - 8.5.3
You want to buy stocks via __invoke() You want to sell stocks __invoke()

preferences:
83 ms | 1491 KiB | 4 Q