Skip to content

Instantly share code, notes, and snippets.

@azjezz
Last active April 22, 2019 23:40
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 azjezz/03955ff2b009f1ced22ce68c9a862847 to your computer and use it in GitHub Desktop.
Save azjezz/03955ff2b009f1ced22ce68c9a862847 to your computer and use it in GitHub Desktop.
$baz as Baz -> passed.
$qux as Baz -> failed : Expected Baz, got Qux.
$baz as Qux -> failed : Expected Qux, got Baz.
$qux as Qux -> passed.
$baz as Foo -> passed.
$qux as Foo -> passed.
$baz as Bar -> failed : Expected Bar, got Baz.
$qux as Bar -> passed.
$baz as string -> failed : Expected string, got Baz.
$baz as int -> failed : Expected int, got Baz.
$str as string -> passed.
$str as int -> failed : Expected int, got string.
$str as bool -> failed : Expected bool, got string.
$num as num -> passed.
$num as int -> passed.
$num as float -> failed : Expected float, got int.
abstract class Foo {}
interface Bar {
public function bar(): void;
}
final class Baz extends Foo {}
final class Qux extends Foo implements Bar {
public function bar(): void {}
}
function test<T>(
string $name,
(function(): T) $test,
): void {
try {
$test();
print $name . " -> passed.\n";
} catch(\Exception $e) {
print $name . ' -> failed : ' . $e->getMessage() . ".\n";
}
}
<<__EntryPoint>>
async function main(): Awaitable<void> {
$baz = new Baz();
$qux = new Qux();
// you can do :
$qux as Qux;
// also
$bar = $qux as Bar;
// this :
$qux as Bar->bar();
// is the same as :
($qux as Bar)->bar();
test('$baz as Baz', () ==> $baz as Baz);
test('$qux as Baz', () ==> $qux as Baz);
test('$baz as Qux', () ==> $baz as Qux);
test('$qux as Qux', () ==> $qux as Qux);
test('$baz as Foo', () ==> $baz as Foo);
test('$qux as Foo', () ==> $qux as Foo);
test('$baz as Bar', () ==> $baz as Bar);
test('$qux as Bar', () ==> $qux as Bar);
test('$baz as string', () ==> $baz as string);
test('$baz as int', () ==> $baz as int);
$str = 'string';
test('$str as string', () ==> $str as string);
test('$str as int', () ==> $str as int);
test('$str as bool', () ==> $str as bool);
$num = 3;
// we don't have `num` in php
test('$num as num', () ==> $num as num);
test('$num as int', () ==> $num as int);
// this should pass in php, as phps' `float` is `num`
test('$num as float', () ==> $num as float);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment