Skip to content

Instantly share code, notes, and snippets.

@xZero707
Created July 24, 2018 20:32
Show Gist options
  • Save xZero707/7c64b27bd108dd16b62bfa7ca1bebdee to your computer and use it in GitHub Desktop.
Save xZero707/7c64b27bd108dd16b62bfa7ca1bebdee to your computer and use it in GitHub Desktop.
<?php
/**
* We declare $x as init of anonymous class, which implements magic __toString() method
* @author Alexander Puharic <xzero@elite7hackers.net>
*/
$x = new class
{
/** @var array */
private $feed;
/**
* Anonymous class constructor.
*/
public function __construct()
{
$this->resetFeed();
}
/**
* Reset counter to initial value
*/
public function resetFeed(): void
{
$this->feed = [
'208',
'103',
'LO',
'FA',
'0'
];
}
/**
* Pop one element from feed
* When feed reaches end, it will be reseted
*
* @return string
*/
public function getFeedElem(): string
{
$elm = array_pop($this->feed);
if (empty($this->feed)) {
$this->resetFeed();
}
return (string)$elm;
}
/**
* Magic happens here, follow comments
*
* @return string
*/
public function __toString(): string
{
return $this->getFeedElem();
}
};
/**
* Demo, to understand what really happens here
*/
for ($i = 0; $i < 10; $i++) {
echo $x . PHP_EOL;
}
/**
* We use lossy comparision here with intention, as PHP will attempt to convert $x to match the string
* (notice that we strictly use strings and not integers in condition)
* This will in turn trigger __toString() method (instance used as string).
* This occurs on every statement in condition, and built-in counter is increased and keeps rising
* until all statements are satisfied.
*/
var_dump(
(empty('' . $x) && ($x == 'FA' && $x == 'LO' && $x == '103' && $x == '208'))
);
@xZero707
Copy link
Author

Initial solution was based on pretty much the same approach, but with counter and some more advanced logic. Good friend of mine, once faced with this challenge wrote elegant solution using array pointers instead, therefore effectively reducing the code and overall complexity.

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