Skip to content

Instantly share code, notes, and snippets.

@paragonie-scott
Last active May 4, 2017 11:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paragonie-scott/60fbd6197929a443de872aee97059f49 to your computer and use it in GitHub Desktop.
Save paragonie-scott/60fbd6197929a443de872aee97059f49 to your computer and use it in GitHub Desktop.
The Trolololol Design Pattern
<?php
declare(strict_types=1);
class Foo
{
/**
* Even if the code that calls isn't using strict_types, it will still TypeError
* if the wrong type is passed.
*/
public function bar($param, $secondParam)
{
return $this->actualbar($param, $secondParam);
}
private function actualBar(string $param, int $secondParam)
{
var_dump($param, $secondParam);
}
}
<?php
// Notice, no strict_types declaration
require 'trololol.php';
$x = new Foo();
$x->bar('abc', 123);
// TypeError:
$x->bar('abc', '123');
/*
string(3) "abc"
int(123)
PHP Fatal error: Uncaught TypeError: Argument 2 passed to Foo::actualBar() must be of the type integer, string given, called in /home/scott/trololol/trololol.php on line 12 and defined in /home/scott/trololol/trololol.php:15
Stack trace:
#0 /home/scott/trololol/trololol.php(12): Foo->actualBar('abc', '123')
#1 /home/scott/trololol/poc.php(11): Foo->bar('abc', '123')
#2 {main}
thrown in /home/scott/trololol/trololol.php on line 15
*/
@paragonie-scott
Copy link
Author

Now implemented as a trait: https://github.com/paragonie/stern

@gabidj
Copy link

gabidj commented May 4, 2017

It's $this->actualBar($param, $secondParam), not $this->actualbar($param, $secondParam)

I know methods are not case sensitive but it still bothers me. :)

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