Skip to content

Instantly share code, notes, and snippets.

@guiwoda
Last active August 29, 2015 14:21
Show Gist options
  • Save guiwoda/5d16c8fb97d29e476d20 to your computer and use it in GitHub Desktop.
Save guiwoda/5d16c8fb97d29e476d20 to your computer and use it in GitHub Desktop.
Simple interfaces to convert objects to scalar types and usage examples
<?php
interface CastsToString {
public function __toString(): string;
}
interface CastsToArray {
public function __toArray(): array;
}
interface CastsToBool { // or CastsToBoolean
public function __toBool(): bool;
}
interface CastsToInt { // or CastsToInteger
public function __toInt(): int;
}
interface CastsToFloat {
public function __toFloat(): float;
}
<?php
// I left an example in the mailing list with a Money object
class Money implements CastsToString, CastsToFloat {
const DOLLARS = '$';
const POUND = '£';
const YEN = '¥';
private $currency;
private $amount;
public function __construct($amount, $currency){
$this->amount = $amount;
$this->currency = $currency;
}
public function __toString(){
return $this->currency . $this->amount;
}
public function __toFloat(){
return $this->amount;
}
}
<?php
// We could do stuff like:
$foo = new Foo(5); // implements CastsToInt
$bar = pow($foo, 2); // internally calls $foo->__toInt()
$collection = new Collection(); // implements CastsToArray
array_walk($collection, 'trim');
if (new CollectionRule($collection)) { // implements CastsToBool
// this one may be tricky, as now objects always evaluate to TRUE.
// But not BC break, as no code implements this interfaces yet
echo 'great!';
}
// Usage of the Money class
$money = new Money(12.5, Money::YEN);
var_dump((string) $money); // string(5) "¥12.5"
var_dump((float)$money); // float(12.5)
@Kubo2
Copy link

Kubo2 commented May 23, 2015

I think this is very great idea 💯 but one thing which is hitting my eyes here is the fact that arrays are not scalars :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment