Skip to content

Instantly share code, notes, and snippets.

@guiwoda
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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)
@heiglandreas
Copy link

Great Idea! But doesn't the ArrayAccess-interface cover the CastToArray-Interface-idea?

@guiwoda
Copy link
Author

guiwoda commented May 13, 2015

@heiglandreas: Not really. I just responded to francois in the mailing list with an example of Traversable, but ArrayAccess aplies all the same: if a method hints for array, the object won't pass the test. You'd have to iterate it somewhere in between messages, and build the resulting array outside of the object.

All of this gets stronger when you consider that our current userland ecosystem is very rich and we constantly use third party objects that we cannot (easily) modify.

@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