Hi Niklas, On Mon, Jan 19, 2015 at 9:42 AM, Niklas Keller <m...@kelunik.com> wrote:
> I'd like to propose a new feature to PHP: The in Operator > Bob mentioned a few weeks ago he wants such an operator in PHP and today I > stumbled over > > http://nikic.github.io/2012/07/27/How-to-add-new-syntactic-features-to-PHP.html > again, > which uses the in operator as a sample. > > Use cases: > > $obj = new StdClass; > $obj->prop = "value"; > $languages = ["PHP", "C", "Java"]; > var_dump("PHP" in $languages); // true > var_dump("Python" in $languages); // false > var_dump(0 in $languages); // false > var_dump("0x0" in ["0e3"]); // false > var_dump("prop" in $obj); // true > var_dump("foo" in $obj); // false > var_dump("Hello" in "Hello World!"); // true > > For strings, it would replace `strpos("Hello World!", "Hello") !== false)`, > for arrays it would replace `in_array($needle, $haystack, true)` > and for objects it would be a replacement of property_exists($class, > $property)`. > > This change would mainly be syntax sugar, but I think it's worth because: > * `"0x0" in ["0e3"]` would return false while `in_array("0x0", ["0e3"])` > returns true, that's probably an edge case, but there may be a lot of > people that don't use the `$strict` parameter, see http://3v4l.org/0K7E5 > * It would solve the issue that it's hard to remember the order of the > arguments for in_array and strpos, just had to look it up again. > > Bob would volunteer to implement that feature. > I would like to reserve 'in' and 'out' for Design by Contract (DbC). http://en.wikipedia.org/wiki/Design_by_contract D language has in and out like function foo() { in { // precondition } out { // postcondition } { // function body } Contract programing can be done only with assert or annotation. However, it's much easier/readable with native language support. Contract programming is proved to be fast/robust/secure. in operator can be useful, but it's the same as in_array(). If we need strict type check, we may do $ php -r 'var_dump(in_array("0x0", ["0e3"], TRUE));' bool(false) as you mentioned. I would like to reserve 'in' for DbC rather than syntax sugar. Regards, -- Yasuo Ohgaki yohg...@ohgaki.net