function chaining for PHP 7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types=1); | |
require_once "✨.🐘"; | |
✨($_)->strlen("foo")->var_dump($_); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php declare(strict_types=1); | |
function ✨(&$_) { | |
return new class($_) { | |
private $_; | |
public function __construct(&$_) { | |
$this->_ = &$_; | |
} | |
public function __call(string $name, array $args): self { | |
$this->_ = $name(...$args); | |
return $this; | |
} | |
}; | |
} |
@Potherca Yep, anonymous classes aren't strictly needed! I originally wrote this as a regular class, but I realised it would be neater and could be used more concisely if I used an anonymous class.
…wait, wouldn't even need a method, if _
was exposed as a public property…
What's the perf impact versus nested calls?
<?php declare(strict_types=1);
function ✨($_) {
return new class($_) {
public $_;
public function __construct(&$_) {
$this->_ = &$_;
}
public function __call(string $name, array $args): self {
$this->_ = $name($this->_, ...$args);
return $this;
}
};
}
$a = 'asd';
echo ✨($a)
->md5()
->strtoupper()
->_;
Awesome
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@sgolemon It could be shorter if I had a method to get the return value. I originally had that in the class when I started writing it, I should maybe add it back.
(The obvious choice of name would be
->_()
, but there's a global PHP function called_
already, which is an alias forgettext
…)