Hello Josh,
- I think it would be better to have ObjectSafe Calls, e.g.
class User {
...
public function delete() {
// delete ...
}
}
class Users {
public function find($id) {
if ($this->db->query(...)) return new User($id);
return 'not found';
}
}
$users = new Users();
$result = $users->find(42)?->delete(); // $result = 'not found';
That way we can use scalars as return for further processing.
Definition:
Calling $obj?->foo(..) behaves identically to $obj->foo(..) if $obj is an object. If $obj is not an $object, then it returns $obj.
- Another approach would to implement this in user land:
class Failure {
public function __construct($msg) {
$this->msg = $msg;
}
public function __call($name, $args) {
return $this;
}
}
class User {
...
public function delete() {
// delete ...
}
}
class Users {
public function find($id) {
if ($this->db->query(...)) return new User($id);
return new Failure('not found');
}
}
$users = new Users();
$result = $users->find(42)->delete();
// do sth...
if ($result instanceof Failure) {
echo $result->msg; // not found
}
Regards
Thomas
Josh Watzman wrote on 10.12.2014 00:07:
Hey internals! A useful feature that Hack picked up in the last few months are
"nullsafe calls", a way of propagating failure forward in a series of chained
method calls to the end of the whole computation, getting rid of a lot of the
boilerplate in the middle. I think the feature would be a good one for PHP as
well, so I'm submitting this RFC to add it -- you can see the RFC itself for a
full discussion of the motivation for the feature, as well as the feature
itself:https://wiki.php.net/rfc/nullsafe_calls
Josh Watzman
Hi Thomas,
- I think it would be better to have ObjectSafe Calls, e.g.
class User {
...
public function delete() {
// delete ...
}
}
class Users {
public function find($id) {
if ($this->db->query(...)) return new User($id);
return 'not found';
}
}$users = new Users();
$result = $users->find(42)?->delete(); // $result = 'not found';That way we can use scalars as return for further processing.
Definition:
Calling $obj?->foo(..) behaves identically to $obj->foo(..) if $obj is an object. If $obj is not an $object, then it returns $obj.
This would prevent adding methods for scalars or arrays in future, so I don’t like it.
Thanks.
Andrea Faulds
http://ajf.me/