Skip to content

Instantly share code, notes, and snippets.

@fowlerwill
Created May 26, 2020 04:52
Show Gist options
  • Save fowlerwill/4f14bfbb3557b92b08a2fd0834c1daa3 to your computer and use it in GitHub Desktop.
Save fowlerwill/4f14bfbb3557b92b08a2fd0834c1daa3 to your computer and use it in GitHub Desktop.
<?php
// Okay, here's something I really like from Kotlin & Swift, they're called Optionals (or Nullable)
// var coolThing: Bool?
// this means that that variable may be one of three values, null, true, or false.
// PHP has had this forever you might say
// $cool_thing = null
// That var could become a string, int, bool, whatever you'd like! But here lies the intersection where
// the typed world can help PHP, I think.
if (!is_null($cool_thing)) {
$cool_thing->doSomethingAwesome();
}
// Writing statements like the above is okay the first few thousand times you do it. In Kotlin / Swift you can
// do that without even noticing it like this:
// coolThing?.doSomethingAwesome();
// Let's see how close we can get to that in PHP...
// Initially I thought of using a function:
function ifLet($variable, $callback) {
if (!is_null($variable)) {
$callback($variable);
}
}
// That's not too bad:
class Main {
/**
* @var string
*/
protected $option;
public function __construct($args) {
if (isset($args['option'])) {
ifLet($args['option'], function($option) {
$this->option = $option;
});
}
}
}
// That's not too bad! But older PHP devs will recognize that in a heartbeat as:
if ($option = $args['option']) {
// do stuff...
}
// That's been done before! We want to see how else we can bend the language.
// Maybe we could use anon objects?
class Q {
public $value = null;
public function __construct($value) {
$this->value = $value;
}
public function __call($name, $arguments) {
if (!is_null($this->value) && method_exists($this->value, $name)) {
call_user_func_array([$this->value, $name], $arguments);
}
}
}
class Person {
public function name() {
return "Fry";
}
}
$not_fry = null;
$fry = new Person();
print( (new Q($not_fry))->name() );
// To be continued...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment