[PHP-DEV] Re: Method compare()

2016-08-09 Thread Stephen Coakley

On 08/09/2016 12:33 PM, David Rodrigues wrote:

Currently PHP has a method called "version_compare()". Should be great
if we have the same function but to general usage. There are some
implementations on web for that, but I guess that it could be done
natively.


compare(mixed $a, mixed $b, string $operator): boolean


Then I could do something like that:


compare(1, 2, '>') === false
compare('1', 1, '===') === false


It should be very useful to libraries that expects that user pass an
operator. For instance:


$collection->where('id', '>', 5) => compare($id, 5, '>')


I guess that it could supports all PHP operators: ==, ===, !=, <>,
!==, <, >, <= and >=.

The spaceship operator does the works too for integers, but not should
works if you expects than $a === $b, or when you expects than $a >=
$b.



See the Comparable RFC for something similar: 
https://wiki.php.net/rfc/comparable


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] [RFC] Pipe Operator

2016-05-09 Thread Stephen Coakley

On 05/09/2016 11:41 AM, Sara Golemon wrote:

On Sun, May 8, 2016 at 11:45 PM, Stanislav Malyshev  wrote:

Neither of these is true for |>-$$ thing - it does not have any matches
in any languages I can think of.


You lack imagination.  Here's three to get you started:

Elixir: 
http://elixir-lang.org/getting-started/enumerables-and-streams.html#the-pipe-operator
F#: https://msdn.microsoft.com/en-us/library/dd233229.aspx#Anchor_11
Clojure: https://clojuredocs.org/clojure.core/-%3E

And if they seem to obscure, how about this proposal for Javascript?
https://github.com/mindeavor/es-pipeline-operator


I am really, truly sorry as this is a serious matter, but I kinda 
laughed a little bit at this burn...


|> seems like a common symbol to use, but it admittedly does look a 
little strange. Hmm? Do I have a better proposal? Nope, not really. It's 
all just syntax in the end.


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: async/await - is future reserved words in PHP 7.x?

2016-05-04 Thread Stephen Coakley

On 05/04/2016 11:44 AM, Niklas Keller wrote:

2016-05-04 16:40 GMT+02:00 Stephen Coakley <m...@stephencoakley.com>:
Why do we have to wait until PHP 8? Should be mostly backwards compatible
and be fine in 7.2 or so. Issue is probably more deciding on an API.



I don't think we should wait, I was just thinking that it might not be 
ready until that time.


Also, if we plan on rewriting streams and I/O to all be async and use 
libuv underneath, that would probably be a BC break unless the existing 
functions just become blocking interfaces for a separate async API. If 
it was a large BC break, it probably would need to wait for PHP 8.


Now that I think about it, that would be our chance to replace stream 
resources with classes...


$file = \php\stream::open("file.txt");
$bytes = await $file->read(1024);
$file->close();

Then rewrite fread() and friends to be aliases that block instead of 
await results.


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: async/await - is future reserved words in PHP 7.x?

2016-05-04 Thread Stephen Coakley

On 05/04/2016 05:59 AM, S.A.N wrote:

EventLoop interface, on development stage:
https://github.com/async-interop/event-loop


That's a userland design for event loops; async/await and coroutines 
don't necessarily depend on an event loop. They could be added to the 
language without an event loop, and simply require the user to provide 
the event loop.


My idea was to make a transition into async as simple as possible.

Also, I'm partially responsible for the event loop interface above. :P


PHP wrappers for libev and libeio supported PHP 7.
https://pecl.php.net/package/ev
https://pecl.php.net/package/eio

>

libuv - certainly better because it has everything you need and a huge
community.


I agree; libuv is probably the best of the bunch, if we include an event 
loop library in future versions of PHP. It is not necessary to have a 
PHP wrapper for libuv, since if it was included in the interpreter 
itself we would be just using the C interface.



Very need async/await in the PHP core (based on generators).
Perhaps there are plans in core developers, for implement async/await?


/Legend speaks of such plans, but they come and go in whispers. Like a 
shadow, or a mist from the east. The prophecy spake of such features 
targeting PHP8; lo, most believe it to be myth./


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] [RFC] Pipe Operator

2016-05-02 Thread Stephen Coakley

On 04/30/2016 06:14 PM, Rowan Collins wrote:

On 29/04/2016 20:58, Sara Golemon wrote:
Let's say I want to add a condition just before getFileArg(); with the
current version I've got to:
- go to the beginning of the chain, and assign to something other than $ret
- go to where I want to break the chain, and reintroduce the $ret
assignment
- add my check in the gap, using the variable I just added at the
beginning of the chain

$fileList = scandir($arg)
 |> array_filter($$, function($x) { return $x !== '.' && $x != '..'; })
 |> array_map(function ($x) use ($arg) { return $arg . '/' . $x; },
$$);
if ( someCheck($fileList) {
 something();
}
$ret = getFileArg($$)
 |> array_merge($ret, $$);

The syntax is fighting me here, making me jump around the code. But if
assignment was always on the end of the chain, I would only need to make
changes at the point where I was breaking the chain. The basic pattern
would be:

|=> $tempVar; // terminate the chain and capture the value
// do stuff with $tempVar
$tempVar // restart the chain

So:

scandir($arg)
 |> array_filter($$, function($x) { return $x !== '.' && $x != '..'; })
 |> array_map(function ($x) use ($arg) { return $arg . '/' . $x; }, $$)
 |=> $fileList;
if ( someCheck($fileList) {
 something();
}
$fileList
 |> getFileArg($$)
 |> array_merge($ret, $$)
 |=> $ret;

If I don't need the condition any more, I can delete lines 4 to 8, and
I've got back my original chain.


Could you use a closure instead to accomplish this? (Again yes, Sara 
could you clarify if this is permitted?)


$ret = scandir($arg)
|> array_filter($$, function($x) { return $x !== '.' && $x != 
'..'; })
|> array_map(function ($x) use ($arg) { return $arg . '/' . $x; 
}, $$)

|> (function($fileList) {
   if (someCheck($fileList)) {
   something();
   }
   return $fileList;
   })($$)
|> getFileArg($$)
|> array_merge($ret, $$);

Not completely the best, but perhaps there's some sort of an idea here?

--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] [RFC] Pipe Operator

2016-05-02 Thread Stephen Coakley

On 04/30/2016 01:05 PM, Larry Garfield wrote:

On 04/29/2016 07:19 PM, Stanislav Malyshev wrote:
In a way... Sara, this syntax feels like it's only one step removed from
promises; if any of the chained steps involve IO, it becomes basically
what promises are for.  Am I barking down the wrong tree, or is there
something we could connect there?  (I don't mean "reject this in favor
of promises", but more "is there something we can do here to be forward
thinking, since lots of people want to see async in core PHP?")

--Larry Garfield


I see the connection to promises too; it's not just you :)

I might be thinking about it wrong, but I think that "one step" you're 
looking for is handling the failure case (Sara kinda mentioned it in a 
later post). Promises are essentially matching two cases: 
Success/Ok/Some, and Failure/Error/None. This RFC seems to only handle 
the first case. Sure, you could use exception handling:


try {
$ret = scandir($arg)
|> array_filter($$, function($x) { return $x !== '.' && $x != 
'..'; })
|> array_map(function ($x) use ($arg) { return $arg . '/' . $x; 
}, $$)

|> getFileArg($$)
|> array_merge($ret, $$);
catch (Throwable $e) {
}

But not all failures or "errors" are actually exceptions. I'm not sure 
how to approach this cleanly without monads, really.


The other issue is with closures and callbacks. Unless, at some point in 
the future when the heroes of PHP gift us with async in the core pipe 
operator is redefined, async operations need to be resumable later.


Consider a small hypothetical I/O example:

$data = new Socket()
|> (function ($socket) {
   // Um, how do I yield/await here? The next pipe function
   // expects an immediate return...
   return $socket->connect(/* ... */);
   })($$)  // <-- also, this is awkward...
|> readUntil($$, '\n')

The benefit of promises is that everything is eventually defined in 
terms of callbacks. That way things can be executed whenever. From my 
understanding (correct me if I'm wrong) the pipe operator does not 
enable this.


Also, +1 for the idea, and +1 for considering the promises case! Using 
the pipe operator for async operations would be super cool!


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: Improving PHP's type system

2016-04-13 Thread Stephen Coakley
On Wed, 13 Apr 2016 10:53:13 -0600, Levi Morrison wrote:

> Continued (hit send by hotkey accident):
> 
> On Wed, Apr 13, 2016 at 10:50 AM, Levi Morrison  wrote:
>> First, some background: several versions of PHP ago authors of
>> functions and methods could only restrict types to the array type or a
>> class/interface type. We slowly added some other types such as callable
>> and primitive types. These tools have been invaluable to those who care
>> about restricting the types of their inputs and outputs. This type
>> information reduces the code each author has to write if they want to
>> restrict to working with certain types and it also provides a form of
>> documentation. Overall these features have been well received and are
>> considered a good thing to do.
>>
>> However, as we have added these new restrictions we still cannot
>> express exactly what types are permitted in some common cases.
>>
>>   1. Return types cannot specify the function will return only type T
>>   or Null.
>>   2. Parameter types cannot express that an iterable type is required.
>> It's common for functions to work a stream of data and it is irrelevant
>> if it is an array or a Traversable object.
>>   3. Parameter types cannot express that that the parameter must
>> implement two different interfaces. For example, requiring a parameter
>> to implement both Countable and Traversable cannot be done.
>>
>> There are some common work-arounds to these issues:
>>
>>   - Omit the type information and rely on documentation.
>>   - Check the parameter type inside the function (eg
>> `assert(is_array($x) || $x instanceof Traversable)`)
>>   - Introduce a new type that embodies the restrictions. If this in an
>> interface it must be implemented by every object you hope to use the
>> restriction with.
>>
>> In some cases these work-arounds are tolerable. However, some of them
>> are really painful.
>>
>>   - Requiring a new supertype is intrusive. Code cannot always be
>> changed to use the new supertype. For example:
>> - Upstream projects that would not benefit from your changes.
>> - Primitives cannot be extended except by altering the engine.
>> In these cases a new type has to be introduced that proxies
>> behavior to the underlying object/primitive.
>>   - Relying on documentation can lead to subtle and hard to diagnose
>> issues when it is used incorrectly. Erroring immediately is sometimes
>> preferable.
>>
>> All of these issues I've outlined can be nicely resolved by adding two
>> new kinds of types to our system: union and intersection types. A union
>> type requires the variable to match at least one of the types. An
>> intersection type requires the variable to match all of the types. The
>> vertical par symbol (OR) is used for unions and ampersand (AND) is used
>> for intersections. For example:
>>
>> function (A | B $var); would require $var to be either type A or
>> type B.
>> function (A & B $var); would require $var to be type A and type B.
>>
>> To accommodate the common use-case of returning some type or Null we
>> would need to formally allow `Null` as an explicit type:
>>
>> function (): T | Null;
>>
>> Since this is a common use case some languages have a short-hand
>> notation to represent a union with Null:
> 
> function (): ?T;
> 
> Examples of such languages include Swift, C#, OCaml and Hack (though the
> symbol is sometimes in the front and sometimes in the back.
> 
> Later today I will be submitting RFCs for each of these proposals.
> Although they can work independently it is helpful to understand the
> overall goal and how they fit together, which has been the purpose of
> this email. Feedback for each RFC will belong in the thread for that
> piece, but discussion about the ideas overall is better suited here.

COOLNESS!! +10

I really like this mindset of a general solution to these stricter types. 
I think it will present a more consistent "interface" for using types 
across PHP in the future.

In general, this is a more general and elegant solution to nullable type 
in properties, hints, and return types.

I am eager to see what you have in those RFCs. 

-- 
Stephen

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] [RFC Discussion] Typed Properties

2016-04-11 Thread Stephen Coakley

On 04/06/2016 11:33 AM, Phil Sturgeon wrote:

We polled pretty hard and had a bunch of discussions about how
multiple declarations should work, and ended up siding with Zeev and
Larry, and all those others saying that type declarations should work
for all just as visibility does currently:


public int $foo, $bar;

$bar here will be int.

Trying to specify another type will resolve in an error. RFC is
updated to match.

We have a few more implementation tweaks to make, then it's off to the
races with this one.



Nice work; I really appreciate all of the hard work done on this RFC. A 
happy camper here with the results.


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] [RFC] Square bracket syntax for array destructuringassignment

2016-04-09 Thread Stephen Coakley

On 04/07/2016 07:37 AM, Lester Caine wrote:


Do we really need to make everything so shorthand that one has no idea
what one is looking at when scanning code?



That's the goal right? We're trying to make Perl 7 here.

Just kidding. I like it because it makes the syntax look consistent with 
the already available short array syntax.


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: [RFC] Square bracket syntax for array destructuring assignment

2016-04-09 Thread Stephen Coakley

On 04/07/2016 07:21 AM, Andrea Faulds wrote:

Hi everyone,

Bob and I have made an RFC which proposes an alternative syntax for list():

https://wiki.php.net/rfc/short_list_syntax

Please tell us your thoughts.

Thanks!


Mhm, yes, I like it a lot! +1

--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: RFC Proposal: Maybe monad and execution timepolymorphic methods

2016-03-22 Thread Stephen Coakley

On 03/21/2016 11:09 PM, Levi Morrison wrote:

This requires you to query state with `isSome()`. This is hardly any
different from a null case, just more code. We can already accurately
distinguish between `null` and another value.

If we want an option for safer PHP code I think we need a safer
construct that requires exhaustive matching (such as Rust's `match`).
I'm not sure how to pull that off.



Certainly. Ideally some sort of `match`, which is listed as future scope 
in the enum RFC. The above definition of a Maybe is just some sort of 
basis for a type. You probably wouldn't use `isSome()` much and would 
use pattern matching on the enum instead.


As much as I do love Rust's type system though, PHP isn't Rust. :)

--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: RFC Proposal: Maybe monad and execution time polymorphic methods

2016-03-21 Thread Stephen Coakley

On 03/21/2016 03:04 PM, Facundo Martinez Correa wrote:

So I want to "return a NULL". I want to express uncertainty, a
nonexistence. But I want to express that I will return something. And I
want to have this NULL checking at interpretation time. I want everything,
and none of the drawbacks. As we say here in Argentina, I want the bread
and the cake. What can we do to have it? After a bit of thought the Maybe
monad came to me.

My experience in Haskell reminded me of this. To have a structure than
represents uncertainty, is the best way to take away the responsibility
from NULL. To express it in no other way. But my experience in Java has
taught me that Optional of something is not a good way to tackle the
problem. I still have to check if my Optional isEmpty. I still have to
check for null. That is because Java has that type erasure after
compilation time that doesn't allow me to play nice with polymorphism. But
maybe PHP can. Maybe PHP will give me the polymorphism at execution time to
discern an empty Maybe from the one that is not. So I don't have to check
for null ever again in my life. So my code can be free of nulls. So I can
express uncertainty and nonexistance, while I return a User from my
repository.

I hope someone would like this idea. I'm also open to suggestions.
Kind regards
Facundo Martínez


First of all, let me confess that I absolutely love monad (or composite) 
types, and I greatly prefer a Maybe over something that may or may not 
be null. There's a slight problem however, and something that will not 
be easy to get around: a lack of generics.


This is an issue with wrapper types in general in PHP, where you want to 
wrap an object in some other type. You lose type safety on the inner 
object, and so I tend to look for a more type-safe solution in PHP. 
There is already a generics RFC out there 
(https://wiki.php.net/rfc/generics) but implementing it won't be trivial.


Implementing (or defining) a good Maybe type also depends on better 
composite/enum types (https://wiki.php.net/rfc/enum is drafted, but 
doesn't support what we need). The classical definition would be 
(hypothetical PHP syntax):


enum Maybe
{
Some {
public function __construct(T $value);
public function isSome(): bool {
return true;
}
public function into(): T {
return $this->value;
}
},
None {
public function isSome(): bool {
return false;
}
public function into(): T {
throw new Error();
}
}
}

Such a definition depends on two different things we don't have right 
now in PHP. Maybe there's a simpler way, but hopefully you have a better 
alternative?


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] [RFC Proposal] var keyword deprecation/removal

2016-03-05 Thread Stephen Coakley

On 03/05/2016 12:26 PM, Walter Parker wrote:

For software written for other people and for projects that don't have
ongoing tech staffs that do tech debt maintenance, they would like to keep
old, working code running. Telling them that they must spend money to
update the software so that the language can look cleaning is often a hard
sell.

  Outside of the PHP world, there are code bases that are 20-30 years old.
See Linux, Apache HTTPD, in-house software at many corporations.

One of the lessons of the Y2K rollover was that software choices made in
the 50-60's (and in some cases the actual software itself) was felt 40-50
years later because the software wasn't rewritten anew every 10-20 years.
Some companies treat software like capital assets and not as expendables.
They want it to last like a house and not be be replaced every 5-10 years
(like many cars).


Walter



That is correct; there are many, many old codebases of many different 
languages out there. However, you need to consider in what way such 
software is maintained. Let's start with Linux and Apache. Both of those 
pieces of software are _not_ in "maintenance" mode. They are both in 
active development, and as such are living, changing codebases that are 
being continually updated to have new features, bugfixes, and 
compatibility with newer compilers, systems, and libraries.


Now consider some in-house software that is in maintenance only, as 
there are also many of those. Assume one such software is written in C. 
Let me ask you: are you going to compile such software with the latest 
version of libc and using the C11 standard with the compiler? Of course 
not! The likelihood of it compiling bug- and error-free is too common, 
with functions removed in C11 and memory layouts changing in the last 30 
years of libc. You would compile such a program with the appropriate 
versions of its dependencies.


Now I'm not saying any of this is good or bad, I'm just saying it the 
way it is. If you have 40+ year old software that you can't afford to 
continually update, you should continue to use the best versions of 
stuff that are still compatible. If you can afford to update small parts 
to be compatible with newer systems, then do so. (I'm talking like 
changing a few lines of code or maybe more to use a new function instead 
of an old, deprecated one.)


In the PHP world (which is a tad bit different, since you can't ship 
"binaries" compiled 10 years ago), the equivalent would be to run 
10-year-old software on the best version of PHP that it is compatible 
with; 5.6 (hopefully; maybe older, maybe newer -- depends on the 
program). Now how long we backport security and bug fixes to old 
versions is a completely different discussion, but I hope you get my 
meaning.


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: [RFC] Traits with interfaces

2016-03-05 Thread Stephen Coakley

On 03/04/2016 01:17 AM, Davey Shafik wrote:

On Thu, Mar 3, 2016 at 2:19 PM, Stephen Coakley <m...@stephencoakley.com>
wrote:


On Wed, 17 Feb 2016 09:25:50 -0500, Kevin Gessner wrote:


Hello internals team!  I'd like to propose an RFC to allow traits to
implement interfaces.

I've noticed s pattern in Etsy's code and elsewhere, where a trait
provides a common implementation of an interface.  Classes that use the
trait are required to also explicitly declare the interface to benefit.
I propose that traits be permitted to declare and implement interfaces.
Classes that use such a trait would then implement the interface, as
though it were declared on the class, without declaring the interface
explicitly.

I believe this small change would be a useful improvement to the OO
system.  I've written a draft RFC, but I don't have karma to create the
wiki page for it.  Could someone please grant wiki karma to my account,
kevingessner?

I don't yet have an implementation, but I'll be starting on one once
I've posted the RFC.  I look forward to your thoughts and feedback.

Thanks in advance -- Kevin

Kevin Gessner Staff Software Engineer etsy.com


tl;dr: +1 and I really think that this language addition is useful and
makes sense.

Wow, I really want this feature. Reminds me of how powerful traits are in
some other languages, such as Rust. It is very common to use traits to
provide a common interface for something, but with some default
implementations.

Logging is a great example. Your interface might look like this (a
familiar one, eh?):

interface Logger
{
 public function log($level, $message, array $context = array());
 public function error($message, array $context = array());
 public function warning($message, array $context = array());
 // etc...
}

where the idea is that the `error()` and such methods are a convenience
for calling `log()` with a specific logging level. Obviously, these
methods will be implemented in the same fashion most of the time; a trait
would be great:

trait LoggerTrait implements Logger
{
 abstract public function log($level, $message, array $context = array
());
 public function error($message, array $context = array()) {
 return $this->log(ERROR, $message, $context);
 }
 // etc...
}

With this approach, I totally agree that allowing the `LoggerTrait` to
implement the interface makes sense; it allows implementation to be
enforced at the trait level. The second proposal that infers the interface
implementation when using the trait is nice too (though not completely
mandatory). It is pretty much the same situation where you do not have to
re-implement an interface when extending a base class that already
implements it.

--
Stephen



The aliases issue is a little more nuanced and potentially confusing,
regardless of this interface thing:

As you can see here: https://3v4l.org/L23LJ

1. If you simply alias (use foo { bar as bat; }) then you end up with an
*additional* method with the new name, the trait method as defined is still
brought in, and _will_ override inherited methods of the same name.

2. if you try to just change the visibility, you get a fatal error (Fatal
error: Trait method bar has not been applied, because there are collisions
with other trait methods), you must create an aliased name with the new
visibility

3. Doing this (visibility + name) _only_ gives you the new method, which is
_different_ behavior to #1

If the third behaved the same as the first, then this would be a non-issue.
Unfortunately, changing this behavior would be a — particularly hard to
diagnose — BC break and therefore cannot happen IMO.

Perhaps we could look at an alternative such as:

- traits can implement interfaces, which would ensure the _trait_ adheres
to it, but _not_ automatically classes use'ing it.
- Add a new syntax: "use Trait with Interface" or "use Trait implements
Interface" or "use Trait { implements Interface; }" which *explicitly*
calls out this usage

Just some off-the-top of my head thinking as an alternative.

- Davey



I freely admit; the method aliasing does pose an interesting issue, and 
may be good enough reason to simply allow enforcing interfaces at the 
trait level and simply force users of the trait to explicitly implement 
the interface themselves. That way it is easy to check compliance -- 
aliasing a method part of the interface on the trait to a different name 
simply breaks the contract.


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: [RFC] Deprecations for PHP 7.1

2016-03-04 Thread Stephen Coakley

On 03/04/2016 03:49 PM, Johannes Schlüter wrote:

On Fri, 2016-03-04 at 12:29 -0600, Stephen Coakley wrote:

Not a complete polyfill, since $newfunc is a closure and not a string,
so you cannot print out the function name. I have no idea if any code
relies on the lambda itself being a string though.


This has impact on a few things, i.e. Reflection or users might guess
the name. Anyways: Take away: A polyfill won't be 100% identical.

However the typical use case should be around usort() or similar where
this doesn't matter.

johannes



I'm not entirely sure about what you mean. On my system, create_function 
returns something like '\x00lambda_1'. Do you mean that users are 
guessing such a string in order to use it? Sounds like the smelliest of 
code smells.


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] [RFC] Deprecations for PHP 7.1

2016-03-04 Thread Stephen Coakley

On 02/18/2016 04:45 PM, Zeev Suraski wrote:



With rand functions, I don't think we need to touch them. For some
applications, low-key randomness is just fine - if you need to shuffle
array of 20 elements or randomize unit test to ensure you're not testing
same value all the time, low-quality randomness is completely fine. For
other applications, there are superior solutions and everybody who needs
them already uses them, but again I see no value in removing those
functions. It would only cause more breakage and make adoption of new
versions (already horrible) even slower.


I think the obvious option here is to make rand() and srand() aliases to 
rand_mt() and srand_mt(), unless I'm missing something very basic, unless I'm 
missing something very basic here..?  I see zero reason to deprecate them and 
break so much code when we can simply 'upgrade' them at zero cost to both us 
and users.


Aliasing to mt_rand() definitely makes sense. With a name like `rand()`, 
everyone will use it just because it is an obvious and common name for 
the normal way to generate random numbers. Aliasing essentially will 
make `rand()` as everyone uses it, better.


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: [RFC] Deprecations for PHP 7.1

2016-03-04 Thread Stephen Coakley

On 03/04/2016 07:53 AM, Johannes Schlüter wrote:

On Thu, 2016-02-18 at 19:57 +, Andrea Faulds wrote:

I've actually used create_function on occasion for programmatically
generating functions (in particular to create a function for each PHP
operator), but it's trivially polyfillable, and it'd be better if
people
were implementing it themselves (and thus knowing it's based on
eval())
than using it directly without this knowledge.


Just as a detail: You can't create a 100% compatible polyfill to
create_function(). create_function() names functions starting with \0.
Functions starting with \0 are hidden from get_defined_functions() and
possibly other places.

php > echo sizeof(get_defined_functions()['user']);
0
php > create_function('', '');
php > echo sizeof(get_defined_functions()['user']);
0
php > eval('function foo() {}');
php > echo sizeof(get_defined_functions()['user']);
1

johannes



Good point. Another approach to a polyfill would be to use a closure then:

function create_function(string $args, string $code)
{
return eval("return function($args) { $code };");
}

$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . 
log($a * $b);');

echo $newfunc(2, M_E) . "\n";

Not a complete polyfill, since $newfunc is a closure and not a string, 
so you cannot print out the function name. I have no idea if any code 
relies on the lambda itself being a string though.


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: [RFC] Deprecations for PHP 7.1

2016-03-04 Thread Stephen Coakley

On 02/18/2016 06:41 AM, Nikita Popov wrote:

Hi internals!

I've created a bulk-deprecation RFC for PHP 7.1:
https://wiki.php.net/rfc/deprecations_php_7_1

I'm using this RFC to collect various deprecations targeting PHP 7.1, as
having individual RFCs for these is too much management overhead. Each
deprecated feature will get its own vote, of course.

This RFC is incomplete -- I'm posting it now so people can suggest other
things that should be deprecated. I expect it to grow over time and don't
plan to vote on it in the immediate future.

Thanks,
Nikita



My stance on deprecations:

> It seems that perfection is attained not when there is nothing more
> to add, but when there is nothing more to remove.
> - Antoine de Saint Exupéry

I'd say any function that provides duplicate functionality, or 
encourages bad practice, should be deprecated. Keeping the standard 
library clean and focused is ideal.


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: [RFC] Traits with interfaces

2016-03-03 Thread Stephen Coakley
On Wed, 17 Feb 2016 09:25:50 -0500, Kevin Gessner wrote:

> Hello internals team!  I'd like to propose an RFC to allow traits to
> implement interfaces.
> 
> I've noticed s pattern in Etsy's code and elsewhere, where a trait
> provides a common implementation of an interface.  Classes that use the
> trait are required to also explicitly declare the interface to benefit. 
> I propose that traits be permitted to declare and implement interfaces. 
> Classes that use such a trait would then implement the interface, as
> though it were declared on the class, without declaring the interface
> explicitly.
> 
> I believe this small change would be a useful improvement to the OO
> system.  I've written a draft RFC, but I don't have karma to create the
> wiki page for it.  Could someone please grant wiki karma to my account,
> kevingessner?
> 
> I don't yet have an implementation, but I'll be starting on one once
> I've posted the RFC.  I look forward to your thoughts and feedback.
> 
> Thanks in advance -- Kevin
> 
> Kevin Gessner Staff Software Engineer etsy.com

tl;dr: +1 and I really think that this language addition is useful and 
makes sense.

Wow, I really want this feature. Reminds me of how powerful traits are in 
some other languages, such as Rust. It is very common to use traits to 
provide a common interface for something, but with some default 
implementations.

Logging is a great example. Your interface might look like this (a 
familiar one, eh?):

interface Logger
{
public function log($level, $message, array $context = array());
public function error($message, array $context = array());
public function warning($message, array $context = array());
// etc...
}

where the idea is that the `error()` and such methods are a convenience 
for calling `log()` with a specific logging level. Obviously, these 
methods will be implemented in the same fashion most of the time; a trait 
would be great:

trait LoggerTrait implements Logger
{
abstract public function log($level, $message, array $context = array
());
public function error($message, array $context = array()) {
return $this->log(ERROR, $message, $context);
}
// etc...
}

With this approach, I totally agree that allowing the `LoggerTrait` to 
implement the interface makes sense; it allows implementation to be 
enforced at the trait level. The second proposal that infers the interface 
implementation when using the trait is nice too (though not completely 
mandatory). It is pretty much the same situation where you do not have to 
re-implement an interface when extending a base class that already 
implements it.

-- 
Stephen

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: RFC Operator Overloading in Userspace

2016-02-01 Thread Stephen Coakley
On Mon, 04 Jan 2016 16:34:21 +, Andrea Faulds wrote:

> Hi Sara,
> 
> Sara Golemon wrote:
>> Patricio Tarantino has asked me to help him propose Operator
>> Overloading in PHP 7.1 (based in part on my operator extension in
>> PECL).  I think we can expose this to usespace as magic methods with
>> very little overhead (the runtime check and dispatch is already there,
>> after all).
>>
>> I do think that the "Future Expansion" section bears following through
>> with as well, but the basic set of methods already hooked for GMP would
>> be a nice start.
>>
>> https://wiki.php.net/rfc/operator-overloading
> 
> While I would like to see operator overloading in PHP, I don't
> particularly like the approach this RFC takes. It seems to take the
> approach C++, Python and so on use where you can simply overload any
> operator as you see fit. While that is arguably useful, it is open to
> abuse. In C++, for example, you can join two file paths by dividing
> them, or write to a stream by bitwise shifting it left by another
> stream. In Python, you repeat a string by finding the product of it and
> an integer. Abusing operator overloading like this harms readability, is
> not necessarily intuitive and is anyway unnecessary: a function or
> method would work just as well in these situations. Also, I'm not sure
> it's a good fit for a dynamic language to make operators do different
> things depending on their operand types. That just creates the
> possibility of unpleasant surprises at runtime, and PHP has enough of
> these already without the possibility of users creating more.
> 
> Luckily, C++ and Python's approach is not our only option. I am quite a
> fan of Haskell's approach to operator overloading, which is less prone
> to abuse. In Haskell, a purely-functional programming language, certain
> operators (and also certain math functions like abs()) are defined as
> part of "typeclasses", somewhat akin to interfaces in classical
> object-oriented languages like Java or PHP. These typeclasses group
> related operations together, and a conforming implementation of that
> typeclass must implement all the operations. For example, there is a
> `Num` typeclass[0] for numbers, which defines the addition, subtraction,
> multiplication, negation, absolute value, sign and
> conversion-from-integer operations. Extending `Num`, there is a
> `Fractional` typeclass[1] for fractional number types, which adds
> fractional division, reciprocal and conversion-from-rational operations.
> There are likewise similar typeclasses for non-numbers, and other
> descendents of `Num` for other kinds of numbers. The approach Haskell
> takes here is not as prone to abuse because you cannot simply implement
> operations as you please: you must implement them as a set. (Though,
> granted, Haskell also discourages overloading abuse by actually letting
> you define custom operators.) With this approach Haskell also achieves
> something else useful, in that you can use typeclasses as a type
> constraint on function parameters and return types. I think it would be
> more worth pursuing a Haskell-style approach in PHP, most likely with a
> hierarchy of magic interfaces.
> 
> All that aside, I have some other issues with the RFC. The set of
> overloadable operators proposed is very small, and I'm surprised it
> doesn't even include the full set of number operations. But
> additionally, if you were to fill in that set, I wonder if it might be
> worthwhile making some of the math functions overloadable as well, since
> otherwise you have an incomplete set of operators: %'s complement is
> intdiv(), not /, and the closest thing we have to a complement of / is
> fmod(). Likewise, since abs() works on integers and floats, perhaps it
> should work on all number types. I don't think GMP currently overloads
> any of these, though, and there is the possibility we might create
> confusion if overloading extended to math functions.
> 
> Another concern I have is the possibility of having __assign_*
> overloads. These would useful for avoiding having to instantiate a new
> object, but there's potential for them to be implemented wrongly, or be
> implemented without their corresponding normal operations. Since we
> don't have any way to make PHP 4-style copy-on-write value classes at
> the moment, I think we should just do the simpler thing and assume we're
> dealing with completely immutable objects, and therefore not have
> __assign_* methods. Similarly, I don't think should have overloads for
> ++ and -- (the proposed /__(post|pre)_(inc|dec)/ methods). Heck, they're
> probably not even that useful, because you could simply check in __add
> or __sub if the operand's absolute value is 1.
> 
> Regarding the possibility of comparison operators, again I think we
> should go the simpler route. For <, <=, >, and >=, we only need one
> overload method, perhaps __cmp, which returns the usual negative, zero
> or positive value to indicate ordering. I can't see a 

[PHP-DEV] Support for writing and executing compiled opcode

2015-11-13 Thread Stephen Coakley

Hello all,

I've been thinking about PHP optimization and distribution, and I would 
like to hear some opinions on introducing a new feature for a future PHP 
7 version. Here's the concept: allow PHP opcode to be both saved after 
parsing a file, and to be loaded and executed, similar to the bcompiler 
extension and the APC bin functions back in the day.


The advantages are clear: libraries and applications could be compiled 
to opcode ahead of time so PHP wouldn't have to compile it again and 
again (assuming you're not already using OPcache).


A new function could be provided to parse a PHP file, but instead of 
executing it, the compiled opcode would be saved to a file. It might 
part of the OPcache extension if it makes sense, and could be called 
opcache_compile_to_file() or something.


Another option would be to add a command-line flag to the interpreter to 
write compiled opcode instead of executing it after parsing.


Another part of the feature would be to enable the interpreter to 
execute compiled opcode scripts directly. This would work for both 
compiled scripts passed to the interpreter, and scripts loaded with 
`include` and `require`. We would probably need to introduce a new file 
extension to specify opcode files. I'd recommend *.phpo or *.phpc.


This is quite similar to Python's ability to execute Python scripts 
compiled to bytecode as *.pyc files. The feature has seen great success 
in Python, mostly for distributing releases of software or deploying to 
a server.


I'm not at this moment planning an RFC, but I'd like to gauge your 
opinions and reactions first.


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Support for writing and executing compiled opcode

2015-11-13 Thread Stephen Coakley

On 11/13/2015 03:45 PM, Sebastian Bergmann wrote:

On 11/13/2015 04:35 PM, Stephen Coakley wrote:

This is quite similar to Python's ability to execute Python scripts
compiled to bytecode as *.pyc files. The feature has seen great
success in
Python, mostly for distributing releases of software or deploying to a
server.


  Correct me if I'm wrong, but this should already be possible with OpCache
  and its filesystem backend in PHP 7.0.

  See http://talks.php.net/froscon15#/php7pcache1 and following for
  details.


That's great! That's about halfway toward what I'm looking for. That 
means that the engine is likely already capable of doing these things -- 
the next step is to be able to execute any given .php.bin file like in 
that talk. The idea would be to be able to bypass the caching mentality 
by executing an already compiled file, instead of checking if the 
original .php file has a corresponding bin file in the cache


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Support for writing and executing compiled opcode

2015-11-13 Thread Stephen Coakley

On 11/13/2015 05:46 PM, Rasmus Lerdorf wrote:

On Nov 13, 2015, at 17:00, Stephen Coakley <m...@stephencoakley.com> wrote:



On 11/13/2015 03:45 PM, Sebastian Bergmann wrote:

On 11/13/2015 04:35 PM, Stephen Coakley wrote:
This is quite similar to Python's ability to execute Python scripts
compiled to bytecode as *.pyc files. The feature has seen great
success in
Python, mostly for distributing releases of software or deploying to a
server.


  Correct me if I'm wrong, but this should already be possible with OpCache
  and its filesystem backend in PHP 7.0.

  See http://talks.php.net/froscon15#/php7pcache1 and following for
  details.


That's great! That's about halfway toward what I'm looking for. That means that 
the engine is likely already capable of doing these things -- the next step is 
to be able to execute any given .php.bin file like in that talk. The idea would 
be to be able to bypass the caching mentality by executing an already compiled 
file, instead of checking if the original .php file has a corresponding bin 
file in the cache


You could simply deploy both the .php and the .bin files to achieve this today.

-Rasmus



Would the bin files not have to be placed in the special OPcache file 
store location though? That seems sub-optimal.


I'm glad it's already possible though. Thanks for the tip.

--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: Friend class/function

2015-11-05 Thread Stephen Coakley

On 11/01/2015 10:04 AM, georges wrote:

​Hi php internals,

I recently discovered ​the "friendship concept" in c++ and i really love
the concept.
And i wonder if the php internals would be interested to implements it in
the next 7.x major version.


​The concept is simple:

It would allow declared "friend"​class method/function to call a
private/protected member of an other class:


The syntax could be like this (for a single friendship):

private function extractDataFromCache() friend myFriendClass1
{

}


or like this for many friendships:

private function extractDataFromCache() friend
{myFriendClass1::method1, myFriendClass2::method1,
myFriendClass3::method1}
{

}


In this way extractDataFromCache() could be called directly by method1 in
myFriendClass1 and myFriendClass2 etc

Off course deep calling should not be allowed. (E.g a function inside
myFriendClass1 that will call extractDataFromCache() won't inherit the
friendship.

Regards,
Georges



As Rowan already wrote, package / namespace visibility is the way to go 
here instead. Personally I found adding "friendship" in C++ to be a poor 
decision, since it's usually a sign of a code smell (not *always* 
though). There are admittedly a couple of use cases, but keeping things 
inside a private namespace is probably a more elegant solution.


I'd support namespace visibility. +1

--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] [VOTE] Void Return Type RFC

2015-11-05 Thread Stephen Coakley

On 10/29/2015 07:44 AM, Dan Ackroyd wrote:

Hi Internals,

Stanislav Malyshev wrote:

every PHP function actually returns
something (at least null). So this type would not actually be right and
would not reflect what actually is happening.


Well obviously we would need to have a followup RFC to make void
functions not have a usable return value! /s

I drafted this email a week ago and didn't send it as I though it was
too snarky to be a useful thing to add to the conversation, but it
seems that it has come up:

François_Laupretre wrote:

Is it too late to add a note in the RFC, listing the possibility, in the
future, to forbid using the result of void functions in expressions.


This is an idea that this RFC obviously leads to, but one that is very bad.

Being able to call a function dynamically and not need to determine
whether it is 'void' return type eliminates a whole class of errors
that can occur when calling code dynamically.

function timeFoo(callable $fn) {
 startTime();
 $result = $fn();
 endTime();

 return $result;
}

This can be done without any inspection on what the return type of
`$fn` is, and is one of the things that PHP got right.

And yes, if we don't make that change, using the pseudo-type of 'void'
instead of 'null' is going to be an instant source of PHPSadness.

Q: This function has a 'void' return type but it's actually returning null?
A: Yes.
Q: Shouldn't it have a 'null' return type?
A: Apparently they chose to make the language follow the manual rather
than make the manual follow the language.
Q: ...Is it too early to start drinking yet?

Tring to 'clean this up' by preventing a void function being used as
an expression, is an example of making the program follow the PHP
manual's convention, rather than making the manual document what the
engine does.

Levi Morrison wrote:

This is one reason I am in favor of `null`
instead of `void`. Void does not accurately portray the semantics in
my opinion. If the return type was null instead of void there would be
no issue. Sure, the return value would be null, but partialLeft
doesn't care – it just passes whatever the result was.


I think this is an important point, and so to try and expand on this a
bit; if you have a function that does not return a value or has a
void/null return type, then this code:

logResult(foo());

is valid.

The person who wrote the function 'foo' might not anticipate that the
function would be used in that way but that is valid code. It is only
when you actually try to use the value as anything other than null
that it becomes a problem i.e.

function findUserbyId(int $userId) {...}
findUserbyId(foo());

it's when you pass the null value to function that needs a non-null
value that the error occurs.

Although alerting someone that they are using a null value where they
actually need another type is a useful thing, we do not need another
type (or pseudo-type) to do this. We should add null as a return type
rather than void as null:

* accurately describes what is happening in the engine, instead of
being an instant source of confusion.
* is compatible with the proposed 'nullable return types' and/or
'union types', void isn't.
* avoids adding a new pseudo-type just for a single use case.

cheers
Dan



These are all excellent thoughts and the same reason why I don't like 
the use of `void` in this RFC. It doesn't accurately describe what is 
happening. Plus introducing even a context-sensitive keyword just for a 
single part of the language "feels" inconsistent.


Now if we want to change how the engine actually handles functions that 
don't return, that's another discussion...


My 2 cents.

--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: Some words about the basic ideas of PHP

2015-10-27 Thread Stephen Coakley

On 10/26/2015 05:09 AM, Frank Meier wrote:

Hi to all of you,

first I want to apologize for may bad English,

.. . .


I write because I feel that that the way how you see your own product PHP
is totally wrong. I do not mean with it that the construction of the
language is wrong.


Ah, OK. So you're the expert then. PHP is open-source; maybe you'd like 
to contribute to make it better?



Your basic aproach is wrong.

PHP is a server side programming language. That means that the most work
what PHP have to do is to be the boss of the data servers and handle the
data.


I mean, that's the primary environment PHP is used in, but it can be 
used for anything really. Straight from the PHP.net homepage:


> "PHP is a popular general-purpose scripting language that is 
especially suited to web development."



Create database or tables  or records,  edit,  delete and read and write
them.

And where is your fantastic programming language so incredible lousy that
me, I am since 35 years a database programmer, just shake my head???

Exact in this operations!!!

I know that it is for free and I can not tell you how much I value your
work on it, but  all of you, WAKE UP


Your tone of voice is a little comically inappropriate, and it doesn't 
sound like you value our work. :)



You sent the handling of records from modern handling via recordsets back
to computer stone age. It is a  torture to use PHP without tools (and they
are lousy too) for database operations.


As already mentioned, try PDO (http://php.net/manual/en/book.pdo.php) -- 
its built-in and is just as easy to use as ADO.


If you want to actually use ADO in PHP, you can do that too with COM 
(http://php.net/manual/en/class.com.php). I'd recommend PDO though; its 
efficient and easy to use.



I can give you a example:

It is in PHP a lot of work to just read the next record in a table.

With ADO is it just nextrecord().

The PHP  way is a insult to the modern world of programming.


Uh, wait. Where's the PHP example that is "a insult to the modern world 
of programming"? You didn't actually give an example for PHP...


Let me help you out.

ADO (note I could be doing this wrong...):
SqlCommand query = new SqlCommand("SELECT * FROM Foo", dbConnection);
dbConnection.Open();
SqlDataReader reader = query.ExecuteReader();

if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}", reader.GetString(0));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();

PDO:
$statement = $dbConnection->query("SELECT * FROM Foo");

if ($statement->rowCount() > 0) {
while ($row = $statement->fetch()) {
print $row[0] . "\n";
}
} else {
print "No rows found.\n";
}


Maybe you should consider to write internal  functions for the record
handling which do take all the sql waste of time away  from the programmer
and create just short command words that the developer can use them.

This would be a "small step  for you but a  huge leap for mankind!".

And you would finally win the race  in the language battle.


Not to brag, but we already did. Some of the biggest websites like 
Wikipedia, use PHP.



I am sorry that I write it so harsh, but PHP is for me the definition of
server data handling and exact there you fail in a big way.


I'm not sure what your evidence is for that, but thanks for the laughs.


All the programmers around the world reinvent every time the wheel new?

Have this really to be?

In my opinion should exist  commands like:
recordnew(table)
recordread(id, table)
recordwrite(id, table)
recorddelete(id, table)
recordprev(currentrecord, table)
recordnext(currentrecord, table)

This is the minimum what I expect from a program language in the year 2015.


No object-oriented programming, iterators, or abstraction, in the year 
2015? Interesting opinion.



This should include already the ajax handling and all the other actions
that are needed to get or view or write the data.


AJAX handling is totally irrelevant here. Not sure what it has to do 
with DB access,



It should also be included table locking and record locking, if needed.

And special  commands for reading multiple records for paginations.
And also for a easy  way to edit a record in this paginations set (page,
count) and write this  back to the MySQL database or whatever database is
used.

.. . .

You are so focused to make PHP better and better that you just forgot to
upgrade the basic commands.

A programmer in the year 2015 should not need to  fetch records and do this
with program code line by line. This was in the year 1982 the case


Is the program just supposed to "guess" how you want to handle the data? 
That's not programming...



.. . .

It reminds me on hotels which always renovate the lobby but never the rooms
for the guests.

.. . .

I am  sorry  to be so critical,  but this was cooking me since long time.

I am database 

Re: [PHP-DEV] async/await - is future reserved words in PHP 7.x?

2015-10-15 Thread Stephen Coakley

On 10/08/2015 04:14 PM, Larry Garfield wrote:

On 10/01/2015 01:59 AM, Stephen Coakley wrote:

So then, in summary, threads & multiprocessing enables you to do more
*work* simultaneously, while async **maximizes the usefulness of each
thread you have**. So using both is actually an incredibly good thing,
but they aren't the same nor accomplish the same thing. I hope what I
said made sense.


Well, you've successfully convinced me that PHP needs both
multi-threading and async IO. I hope you're happy now...

--Larry Garfield


Quite happy. Sorry about that... :)

--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: async/await - is future reserved words in PHP 7.x?

2015-10-01 Thread Stephen Coakley

On 09/29/2015 11:15 AM, Daniel Lowrey wrote:

On Sep 28, 2015, at 3:29 AM, S.A.N  wrote:> > Are there any future plans 
for - async/await?> This need to know now, not to use these words to constants, and class names...> 
> -- > PHP Internals - PHP Runtime Development Mailing List> To unsubscribe, visit: 
http://www.php.net/unsub.php>


Would this be awesome? Yes. The issue is that all of PHP's built-in IO
operations are currently synchronous. It would/will require a massive
effort to (1) install the infrastructure to offload blocking operations to
worker threads and/or (2) convert many synchronous IO operations to a
non-blocking paradigm. Someone has to do that work ... and it's a lot. I
don't personally see this happening before 8.0 though I'd be happy to be
surprised.

FWIW I'm a big proponent of libuv here and think we could significantly
improve PHP as a language by incorporating it to solve this (and other)
outstanding issues in a cross-OS manner.

In the nearer term, this is exactly the sort of thing the Generator Return
and Generator Delegation RFCs implemented in 7.0 are designed to handle.
With a minimal amount of userland code you can resolve coroutines in
userland as lightweight threads in which IO is accomplished with
non-blocking libraries.

The obvious drawbacks to using yield in userland as a surrogate for
async/await is the proliferation of non-standard userland libraries (of
which several good options already exist) to manage IO, timers and event
loops.

IMHO userland shouldn't know anything about *how* concurrency is achieved
(whether using threads or nbio). With something like libuv internal C code
would have access to a built-in worker thread pool designed specifically
for a non-blocking paradigm. This would allow us to expose the best of both
worlds.

Just my $0.02 on the topic.



I think we can spoonfeed the massive undertaking a bit by spreading it 
across several iterations just to get things going. An idea I had was to 
just begin by providing coroutines as part of the language. That would 
include a `\Coroutine` class, as well as await / async keywords. This 
would at least enable third party async libraries to be more compatible 
since they would have the same await types and semantics.


The next step (or at the same time as the first) is to provide some sort 
of `\EventLoopInterface` along with


\EventLoop::getLoop(): \EventLoopInterface
\EventLoop::setLoop(\EventLoopInterface)
\EventLoop::run()
\EventLoop::stop()
\EventLoop::tick()

To start out, just provide the internal coroutine scheduler as a default 
implementation. Coroutines would use the "event loop" to schedule resumes.


Doing so would allow even more interoperability if a library chose to 
implement `\EventLoopInterface` in its event loop, where it handles 
coroutine scheduling (or lets it fall back to the internal one), and 
could also provide I/O "extras".


The final step would be to bring libuv into PHP, itself as a better 
default implementation of `\EventLoopInterface`.


Just my idea.

--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: Arrow function expressions in PHP

2015-10-01 Thread Stephen Coakley

On 09/26/2015 11:17 AM, Levi Morrison wrote:

(Email in gist format:
https://gist.github.com/morrisonlevi/fa7984c04ff176b5a87c)

In EcmaScript 2015 (ES6) the expression `(x) => x * 2` means to create
an anonymous function with one parameter `x` that will return `x * 2`.
For example:

 (x) => x * 2
 // is equivalent to:
 function(x) { return x * 2; }

A modified example from [documentation by Mozilla Developer
Network][1] page demonstrates how they are useful:

 var a = [
 "Hydrogen",
 "Helium",
 "Lithium",
 "Beryl­lium"
 ];

 var a2 = a.map(function(s){ return s.length }); // pre-ES6

 var a3 = a.map((s) => s.length); // ES6

There has been some talk about how we can use arrow function
expressions in PHP. In PHP using the same syntax would have some
ambiguities:

 // Does this mean:
 //   1. Create an array key with the result of `($x)` and a value
with `$x * 2`
 //   2. Create an array with one value that is an anonymous function
 [($x) => $x * 2]

 // Does this mean:
 //   1. Yield a key with the result of `($x)` and a value with `$x * 2`
 //   2. Yield an anonymous function
 yield ($x) => $x * 2;

This is why Bob Weinand [proposed][2] using `~>` instead of `=>`.
However, if we allow type declarations there is another issue. In the
definition `(Type &$x) => expr` the `(Type &$var)` part can parse as
"take constant `Type` and variable `$var` and do a bitwise and `&`
operation." After that the `=>` will be an unexpected token. Even
though the rule would be invalid the parser doesn't know that far
ahead it will error and it doesn't know which rule to pick. Changing
the token from `=>` to `~>` doesn't affect this issue.

We could solve the first ambiguities with prefering the current
meaning with `key => value` and requiring the meaning with closures to
wrap them in `()`. We could solve the latter ambiguity with a
backtracking parser since it will eventually error and then know to
pick the other rule. However, I really think this is a bad idea.

So how can we have shorter closures without this mess? One simple way
is to require the `function` prefix:

 // clearly an array with an anonymous function
 [function($x) => $x * 2];

 // clearly yields an anonymous function
 yield function($x) => $x * 2;

 // clearly an anonymous function
 function(Type &$x) => expr;

Requiring the `function` prefix mitigates one of the value parts of
arrow functions: they are short.

Another option would be to resolve the ambiguities with keys and
values but to change the type information in parameters:

 (&$input: array) => expr

By putting the type after the variable (similar to how we declare
return types) we no longer have the issues with mis-parsing. Of
course, that's not how we declare parameter types currently. I think
we would need to permit it everywhere and deprecate the current syntax
with the type being prefixed. (By deprecate I mean in PHP 8 and not
remove it until PHP 9 or later)

I would prefer that we shorten the `function` keyword to `fn`:

 [fn($x) => $x * 2]

This preserves the shortness of the expression while providing
unambiguous, simple parsing. Of course, now we have a similar issue:
we have both `fn` and `function`.

What concerns do you have about `fn($x) => $x * 2` or `function($x) =>
$x * 2`? I will be writing a proper RFC later but I wanted to get
discussion going now.

   [1]: 
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
   [2]: https://wiki.php.net/rfc/short_closures



If my opinion is worth anything, I actually like how fn($x) => $x * 2 
looks the most. It's fairly short like the original proposal, but has 
the advantage of *clearly* appearing to be a function. That was a large 
complaint on the whole "short closures" idea in the first place, and PHP 
usually does a good job at making code very obvious and clear.


So yeah, an "fn" prefix (and requiring parenthesis always) looks very 
consistent, but still is short.


> I would prefer that we shorten the `function` keyword to `fn`:

Do you mean generally, or just in short closures? Turning the keyword 
everywhere would be a huge BC break (though pretty easy to fix in code: 
"s/function\s/fn /g" :-) ). I'd be OK with allowing both everywhere for 
consistency though:


fn square(int $x) {
return $x * $x;
}

$squaresPlusOne = array_map(function(int $x) => square($x) + 1, [1, 
2, 3, 4]);


class Foo {
public fn __construct() {}
}

You get the idea...

I actually really like that + your idea. Kudos.

--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] async/await - is future reserved words in PHP 7.x?

2015-10-01 Thread Stephen Coakley

On 09/29/2015 10:22 AM, Thomas Hruska wrote:

On 9/29/2015 6:52 AM, Joe Watkins wrote:

We shouldn't reserve words on a whim ...

async/await doesn't solve any problems for multithreaded programming, at
all ... it solves problems for asynchronous programming, a different
concept ... let's not confuse the two ...


Agreed, the concepts are quite different, thought they can be related in 
a way. More on that in a minute...



Actually, it does.  Asynchronous and multithreaded programming are
attempts at solving the exact same problem:  Simultaneously handling
multiple data streams in whatever form that takes whether that be
network, hard drive, random device XYZ, RAM, or even CPU.  The former
says, "Let's wait until we can read or write and continue when we have
data."  The latter says, "Let's read and write but let the OS handle
context switching to give the appearance of simultaneously handling
multiple data streams."


Actually, they *don't* attempt to solve the same problem (though some 
problems can be solved with either). Concurrent programming (threads, 
forks, or anything else that uses multiple execution contexts -- 
multiple program counters) has the purpose of enabling you to do two or 
more things at once (as much as possible on the current CPU).


If you need to do two big ass math calculations, you can use 
multithreading to do both at once. (I'll ignore instruction pipelining 
restrictions and the context switching overhead curve for simplicity.) 
In this example, asynchronous programming does nothing for us.


If you need to handle 1 socket connections, threading isn't 
practical with a thread-per-connection model. Here, async becomes useful 
because the bottleneck is I/O, not CPU operations. Async programming 
allows you to do other things instead of blocking the thread when doing 
an I/O operation (... or a few other operation types).


So then, in summary, threads & multiprocessing enables you to do more 
*work* simultaneously, while async **maximizes the usefulness of each 
thread you have**. So using both is actually an incredibly good thing, 
but they aren't the same nor accomplish the same thing. I hope what I 
said made sense.


Now, on to async / await. :)


Async/await is both the best of and THE solution to both worlds.  It
...


Yes. But not for the reason that I think you're thinking. Combining 
concurrency with asynchronicity is the best of both worlds, and using 
threads themselves in a non-blocking way with async / await (which are 
strictly an async thing) is pretty powerful. Here's an example (in .NET):


static async void SlowAsync()
{
// Create a task which will be run in the threadpool
Task task = new Task(SlowAssOperation);
	// Asynchronously wait (using the .NET event loop) for the thread to 
complete

await task;
}

static void SlowAssOperation()
{
// Do something synchronous
Thread.Sleep(5000);
}

The fact that we can await something being run in a thread isn't a 
property of threads, but a property of the .NET async event loop which 
can listen for thread events without blocking.


Hope that clears some things up. Sorry for being long winded. :)

--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] async/await - is future reserved words in PHP 7.x?

2015-10-01 Thread Stephen Coakley

On 09/29/2015 01:04 PM, S.A.N wrote:

Implementing elegant, readable, and stable asynchronous code in userland PHP 
code is very possible. In fact, I’ve done exactly this with Icicle 
(https://github.com/icicleio/icicle). Icicle uses generators and promises to 
implement coroutines. When a coroutine yields a promise, the coroutine is 
interrupted until the promise resolves, sending or throwing the resolution 
value into the generator. While a coroutine is interrupted, other code in the 
program is given the chance to be executed. This behavior is similar to 
async/await, instead using a generator as the async function and yield as 
await. There are several packages available for Icicle that implement 
non-blocking I/O and concurrency (multithreading). There are no extensions 
required for Icicle and no black magic – just making good use of the tools 
already available.



My experience says that callback, promise, yield, not transparent as
the async/await in С#.
In other languages:

Python - coroutines with async and await
https://www.python.org/dev/peps/pep-0492/

ECMAScript
https://github.com/lukehoban/ecmascript-asyncawait


Agreed, though in both languages, async / await started out by using 
generators (yield) and futures (promises & callbacks). In JavaScript's 
case, the implementation is actually still built on top of generators.


So, I'm confident we'll get there eventually.


When Node.js appear async/await, many developers and projects will
migrate to a Node.js, if PHP is not implement async APIs.

Hopefully, Dmitry Stogov and others, will make another surprise:
PHP-Next-Async? :)



OT: I don't have any numbers, but I'm not so sure as many people 
"switched" to Node.js as people claim. Node.js has a similar, but 
distinct, goal that is different from PHP's.


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: Arrow function expressions in PHP

2015-10-01 Thread Stephen Coakley

On 10/01/2015 06:52 AM, Levi Morrison wrote:

On Wed, Sep 30, 2015 at 11:59 PM, Stephen Coakley <m...@stephencoakley.com> 
wrote:

On 09/26/2015 11:17 AM, Levi Morrison wrote:


(Email in gist format:
https://gist.github.com/morrisonlevi/fa7984c04ff176b5a87c)

In EcmaScript 2015 (ES6) the expression `(x) => x * 2` means to create
an anonymous function with one parameter `x` that will return `x * 2`.
For example:

  (x) => x * 2
  // is equivalent to:
  function(x) { return x * 2; }

A modified example from [documentation by Mozilla Developer
Network][1] page demonstrates how they are useful:

  var a = [
  "Hydrogen",
  "Helium",
  "Lithium",
  "Beryl­lium"
  ];

  var a2 = a.map(function(s){ return s.length }); // pre-ES6

  var a3 = a.map((s) => s.length); // ES6

There has been some talk about how we can use arrow function
expressions in PHP. In PHP using the same syntax would have some
ambiguities:

  // Does this mean:
  //   1. Create an array key with the result of `($x)` and a value
with `$x * 2`
  //   2. Create an array with one value that is an anonymous function
  [($x) => $x * 2]

  // Does this mean:
  //   1. Yield a key with the result of `($x)` and a value with `$x *
2`
  //   2. Yield an anonymous function
  yield ($x) => $x * 2;

This is why Bob Weinand [proposed][2] using `~>` instead of `=>`.
However, if we allow type declarations there is another issue. In the
definition `(Type &$x) => expr` the `(Type &$var)` part can parse as
"take constant `Type` and variable `$var` and do a bitwise and `&`
operation." After that the `=>` will be an unexpected token. Even
though the rule would be invalid the parser doesn't know that far
ahead it will error and it doesn't know which rule to pick. Changing
the token from `=>` to `~>` doesn't affect this issue.

We could solve the first ambiguities with prefering the current
meaning with `key => value` and requiring the meaning with closures to
wrap them in `()`. We could solve the latter ambiguity with a
backtracking parser since it will eventually error and then know to
pick the other rule. However, I really think this is a bad idea.

So how can we have shorter closures without this mess? One simple way
is to require the `function` prefix:

  // clearly an array with an anonymous function
  [function($x) => $x * 2];

  // clearly yields an anonymous function
  yield function($x) => $x * 2;

  // clearly an anonymous function
  function(Type &$x) => expr;

Requiring the `function` prefix mitigates one of the value parts of
arrow functions: they are short.

Another option would be to resolve the ambiguities with keys and
values but to change the type information in parameters:

  (&$input: array) => expr

By putting the type after the variable (similar to how we declare
return types) we no longer have the issues with mis-parsing. Of
course, that's not how we declare parameter types currently. I think
we would need to permit it everywhere and deprecate the current syntax
with the type being prefixed. (By deprecate I mean in PHP 8 and not
remove it until PHP 9 or later)

I would prefer that we shorten the `function` keyword to `fn`:

  [fn($x) => $x * 2]

This preserves the shortness of the expression while providing
unambiguous, simple parsing. Of course, now we have a similar issue:
we have both `fn` and `function`.

What concerns do you have about `fn($x) => $x * 2` or `function($x) =>
$x * 2`? I will be writing a proper RFC later but I wanted to get
discussion going now.

[1]:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
[2]: https://wiki.php.net/rfc/short_closures



If my opinion is worth anything, I actually like how fn($x) => $x * 2 looks
the most. It's fairly short like the original proposal, but has the
advantage of *clearly* appearing to be a function. That was a large
complaint on the whole "short closures" idea in the first place, and PHP
usually does a good job at making code very obvious and clear.

So yeah, an "fn" prefix (and requiring parenthesis always) looks very
consistent, but still is short.


I would prefer that we shorten the `function` keyword to `fn`:


Do you mean generally, or just in short closures? Turning the keyword
everywhere would be a huge BC break (though pretty easy to fix in code:
"s/function\s/fn /g" :-) ). I'd be OK with allowing both everywhere for
consistency though:

 fn square(int $x) {
 return $x * $x;
 }

 $squaresPlusOne = array_map(function(int $x) => square($x) + 1, [1, 2,
3, 4]);

 class Foo {
 public fn __construct() {}
 }

You get the idea...

I actually really like that + your idea. Kudos.


I am definitely not propo

Re: [PHP-DEV] Re: Arrow function expressions in PHP

2015-10-01 Thread Stephen Coakley

On 10/01/2015 06:52 AM, Levi Morrison wrote:
> On Wed, Sep 30, 2015 at 11:59 PM, Stephen Coakley 
<m...@stephencoakley.com> wrote:

>> On 09/26/2015 11:17 AM, Levi Morrison wrote:
>>>
>>> (Email in gist format:
>>> https://gist.github.com/morrisonlevi/fa7984c04ff176b5a87c)
>>>
>>> In EcmaScript 2015 (ES6) the expression `(x) => x * 2` means to create
>>> an anonymous function with one parameter `x` that will return `x * 2`.
>>> For example:
>>>
>>>   (x) => x * 2
>>>   // is equivalent to:
>>>   function(x) { return x * 2; }
>>>
>>> A modified example from [documentation by Mozilla Developer
>>> Network][1] page demonstrates how they are useful:
>>>
>>>   var a = [
>>>   "Hydrogen",
>>>   "Helium",
>>>   "Lithium",
>>>   "Beryl­lium"
>>>   ];
>>>
>>>   var a2 = a.map(function(s){ return s.length }); // pre-ES6
>>>
>>>   var a3 = a.map((s) => s.length); // ES6
>>>
>>> There has been some talk about how we can use arrow function
>>> expressions in PHP. In PHP using the same syntax would have some
>>> ambiguities:
>>>
>>>   // Does this mean:
>>>   //   1. Create an array key with the result of `($x)` and a value
>>> with `$x * 2`
>>>   //   2. Create an array with one value that is an anonymous 
function

>>>   [($x) => $x * 2]
>>>
>>>   // Does this mean:
>>>   //   1. Yield a key with the result of `($x)` and a value 
with `$x *

>>> 2`
>>>   //   2. Yield an anonymous function
>>>   yield ($x) => $x * 2;
>>>
>>> This is why Bob Weinand [proposed][2] using `~>` instead of `=>`.
>>> However, if we allow type declarations there is another issue. In the
>>> definition `(Type &$x) => expr` the `(Type &$var)` part can parse as
>>> "take constant `Type` and variable `$var` and do a bitwise and `&`
>>> operation." After that the `=>` will be an unexpected token. Even
>>> though the rule would be invalid the parser doesn't know that far
>>> ahead it will error and it doesn't know which rule to pick. Changing
>>> the token from `=>` to `~>` doesn't affect this issue.
>>>
>>> We could solve the first ambiguities with prefering the current
>>> meaning with `key => value` and requiring the meaning with closures to
>>> wrap them in `()`. We could solve the latter ambiguity with a
>>> backtracking parser since it will eventually error and then know to
>>> pick the other rule. However, I really think this is a bad idea.
>>>
>>> So how can we have shorter closures without this mess? One simple way
>>> is to require the `function` prefix:
>>>
>>>   // clearly an array with an anonymous function
>>>   [function($x) => $x * 2];
>>>
>>>   // clearly yields an anonymous function
>>>   yield function($x) => $x * 2;
>>>
>>>   // clearly an anonymous function
>>>   function(Type &$x) => expr;
>>>
>>> Requiring the `function` prefix mitigates one of the value parts of
>>> arrow functions: they are short.
>>>
>>> Another option would be to resolve the ambiguities with keys and
>>> values but to change the type information in parameters:
>>>
>>>   (&$input: array) => expr
>>>
>>> By putting the type after the variable (similar to how we declare
>>> return types) we no longer have the issues with mis-parsing. Of
>>> course, that's not how we declare parameter types currently. I think
>>> we would need to permit it everywhere and deprecate the current syntax
>>> with the type being prefixed. (By deprecate I mean in PHP 8 and not
>>> remove it until PHP 9 or later)
>>>
>>> I would prefer that we shorten the `function` keyword to `fn`:
>>>
>>>   [fn($x) => $x * 2]
>>>
>>> This preserves the shortness of the expression while providing
>>> unambiguous, simple parsing. Of course, now we have a similar issue:
>>> we have both `fn` and `function`.
>>>
>>> What concerns do you have about `fn($x) => $x * 2` or `function($x) =>
>>> $x * 2`? I will be writing a proper RFC later but I wanted to get
>>> discussion going now.

[PHP-DEV] Re: RFC: Generics

2015-09-25 Thread Stephen Coakley

On 09/24/2015 03:43 PM, Dominic Grostate wrote:

Hi Ben & Internals,

I spent most of today and yesterday just getting used to the parser
language.
I was able to implement the basic syntax on most of the constructs, just to
get a partial proof of concept going.

https://github.com/orolyn/php-src/commit/ee731240eab1e5986152cadaaca6d3e5b921ba7d

The generic patterns aren't actually used, this simply "allows" them to be
present.  Also I haven't yet cleaned up the memory leaks.
The hitch I ran into however was function calls.

add_to_collection($collection, $object); // Sorry for the rather
pointless example.

This potentially matches an expression, therefore yacc can't use it.

Another (minor) but annoying issue is that nested generics need to be
written like:

A // Note the space before the last '>'
Else it will match T_SL

I don't know if either of these issues can be neatly corrected, ##parsers
told me it was impossible without some
major hackery, so this might warrant discussion on the tokens used to
define generic delimitation.

Anyway see parsable example below.

Dominic

 {}

class K {}

class A extends K implements Y, Z
{
 public function add(K > $a): Y
 {
 }
}

function sample(A $a) {
 echo 'OK' . PHP_EOL;
}

sample(new A());



I know this is just some experimentation, but requiring a space in 
nested templates would be ugly, so we'd want to figure something out to 
get around that. C++ initially required a space as well and it confuses 
people still to this day.


Thanks for doing this work so far.

--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: Let's discuss enums!

2015-09-17 Thread Stephen Coakley

On 09/17/2015 06:06 PM, Rowan Collins wrote:

Hi All,

This has come up in passing a few times recently, but I'm not sure
there's ever been a dedicated discussion of it: would it be useful for
PHP to have a built-in Enumeration type, and if so, how should it look?

Many other languages have enum types, with varying functionality. The
central concept is always that there's some declared type with a bunch
of named constants, but beyond that there's a lot of variability: for
starters, is it a type of object, a special way of naming integers, or
an uncomparable type more like booleans and nulls?


Here are my thoughts on what I'd like from a PHP enum - I'm not using
"should" in a particularly strong sense, it's just a way of framing the
points of discussion:

1) enums should act like values, not mutable objects; an array-style
copy-on-write behaviour would be possible, but it feels wrong to me to
store any state in an enum variable, so just plain immutable would be my
preference

2) the members of an enum should have a name which is accesible as a
string, e.g. Weekdays::SUNDAY->getName() == 'SUNDAY'

3) there should be no accessible "value" for a member; the value of
Weekdays::SUNDAY is simply Weekdays::SUNDAY, not 0 or 7 or 'SUNDAY' (I'm
thinking that internally, each member would be represented as an object
pointer, so there's no real benefit to forcing people to number
everything like some languages do)

4) each enum member should be considered a singleton, in the sense that
you can't construct or destroy one, only reference them; all possible
instances would be created as soon as the enum was defined

5) following from (3) and (4), an enum value should compare equal only
to itself, unlike in C# for instance, where it would be comparable to an
integer based on its numeric value; similarly it shouldn't be possible
to cast to or from an enum

6) an enum should be able to have additional fields; these would be
initialised in the enum's definition; this is inspired by Java and
Python's ability to pass parameters to the "constructor" of the enum,
but it feels weird to me for any logic to happen in that constructor
other than simple assignments, so I'm thinking of a simpler syntax and
implementation. It also simplifies immutability if no userland code ever
writes to the properties. There may be an important use case for
constructor logic I'm missing though?

7) an enum should have default static methods for accessing all the
members of the enum as an associative array

8) enums should be a first-class type, is_object(Weekdays::SUNDAY)
should return false, for instance; maybe Weekdays::SUNDAY instanceof
Weekdays should return true though

9) additional static and instance methods should be definable, bearing
in mind the immutability constraints already discussed


Given the above, I think we might end up with something like this:

enum Weekdays {
 member MONDAY; // if there are no fields to initalise, the member
just needs its name declaring
 member TUESDAY ( 2, 'Chewsdae' ); // positional arguments for
populating fields in the order they are defined; a bit like Java, but
without the constructor
 member WEDNESDAY { $dayNumber = 3, $sillyName = 'Wed Nose Day' };
// or maybe a named-parameter syntax to make things clearer
 member THURSDAY, FRIDAY, SATURDAY, SUNDAY; // don't force people to
write each entry on its own line; maybe even the "member" keyword is too
much?


Member is even a little too much IMO. A comma-separated list syntax 
would be better, simply because its shorter and more similar to enum 
syntax on other languages.



 public $dayNumber, $sillyName; // fields initialised for each member

 public static function getWeekend() {
  return [ self::SATURDAY, self::SUNDAY ];
 }

 public function getZeroIndexedDayNumber() {
  return $this->dayNumber - 1;
 }
}

$today = Weekdays::THURSDAY;
foreach ( Weekdays::getMembers() as $day_name => $day ) {
 echo $day->dayNumber;
 if ( $day == $today ) {
echo "Today!";
 } else {
echo $day_name; // equivalently: echo $day->getName();
 }
}

// Do we need a static method to access a member by name, or is this
good enough?
$favourite_day = Weekdays::getMembers()[ $_GET['fav_day'] ];


Not sure if this could be allowed, but simply using name interpolation 
would be better. e.g.:


> $favourite_day = Weekdays::$_GET['fav_day'];

Similar to $object->$name and nothing to do with StaticClass::$property 
syntax.



So, what are anyone's thoughts? Am I rambling on too much as usual? ;)

Regards,



Is there any interest in enum subtypes? As in, allowing each member to 
also be a class? This would allow algebraic data typing, which would be 
a pretty powerful addition to the language.


--
Stephen

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: Generic classes and methods RFC

2015-09-09 Thread Stephen Coakley

On 09/07/2015 02:02 PM, George Bond wrote:

On 7 September 2015 at 11:37, Ben Scholzen  wrote:


Hello,

Hi Ben!


Generics are a feature I'd love to see in PHP. I think this RFC could do
with a little elaboration, though.

Something that's particularly important to me is if it be possible to
have default values for type parameters? For example, could I make a
class like this?

  
  {
  private $array = [];

  // ...

  public function append(T $value) {
  $this->array[] = $value;
  }
  }

  $integerList = new List; // only accepts integers
  $list = new List; // accepts any value

Here, 'mixed' means any type, like in the PHP manual or in Hack. We
don't currently have a 'mixed' typehint since we don't need it (you can
simply omit a typehint for a parameter or return type), but it would be
useful here.

I'd like it if this was possible, because then you could make existing
classes use generics without breaking compatibility. It's also more
beginner-friendly: people who don't know about generics don't have to
use them, if the class author has made this possible. This is in keeping
with the "PHP way" where we don't require people to use type hints if
they don't want them.



I'm not sure if we would need any other default than "mixed". Personally I
think that you should be able to instantiate any generic class which does
not enforce specific types on the hints without any types, which
automatically turns it into a mixed-type generic. That should cover this
use-case pretty easily.

On a different note, I'm not sure I like the  `class Baz`

syntax. For functions parameters, we put the type name before the
variable name, e.g. `function foo(int $bar)`. So, could we do the same
here, i.e. `class <\Bar Foo>`, for consistency?



As written in an earlier mail, the colon came up from another email, I'm
happy to change it if there's a better suggestion.


Though that looks a little strange to me. It's two bare identifiers next

to eachother (`\Bar Foo`), unlike function parameters where the second
one has a dollar prefix (`\Bar $foo`). Perhaps type variables, like
regular variables, should have some sort of sigil in PHP? This would
make it more obvious that something is a type variable and not a class
name. To take an example from your RFC, consider the following code
snippet:

  class Entry
  {
  // ...

  public function __construct(KeyType $key, ValueType $value)
  {
  // ...
  }

  // ...
  }

If we hadn't seen the class declaration at the top which makes `KeyType`
and `ValueType` be type parameters, we might not realise they weren't
ordinary classes or interfaces when we looked at `__construct`. The
-Type suffix you've used helps a little, but that's a convention, and
isn't guaranteed to be used. Also, in some existing projects, there
might be classes with that suffix.

What if we use some sort of sigil here to make it clear? Say we used %:

class Entry<%KeyType, %ValueType>
{
  // ...

  public function __construct(%KeyType $key, %ValueType $value)
  {
  // ...
  }

  // ...
}

Now, without having to look at the class declaration, we can tell that
`KeyType` isn't a class name, because it has % in front of it.



I like that idea, as it makes the code easier to understand. I'm wondering
what other people's thoughts about that is.


You could also just use the dollar sign for type variables. As in

class Entry<$KeyType, $ValueType>
{
// ...
public function __construct($KeyType $key, $ValueType $value)
{
// ...
}
// ...
}

Not sure if that would be *more* confusing or *less* confusing. If there 
was such a thing as a "type" type, then, depending on how generics were 
implemented, the type variables could *literaly* be "type" variables. If 
that makes any sense at all.


You could also have the type variables resolve to type strings somehow. 
For example, the output of:


class Box<$T>
{
public function __construct($T $value)
{
// ...
}

public function printType()
{
print "$T\n";
}
}

$box = new Box<\My\Object>(new \My\Object());
$box->printType();

would be "My\Object". Just another idea; one that feels very "PHP-like" 
to me anyway. Other opinions?



Anyway, all that being said: the big challenge with generics is really

getting someone to do the nitty-gritty of implementing it. It's great
that you've got an RFC written for this, but unless someone is willing
to implement it, I fear it may go to waste. But you writing an RFC might
inspire someone. There is hope!



I hope so as well!

Hope my thoughts are somewhat helpful.


--
Andrea Faulds
http://ajf.me/



--
Ben Scholzen
http://www.dasprids.de



I'm a fan of the C# syntax for generics ("where" keyword).  I 

Re: [PHP-DEV] Move internals discussion to a better medium

2015-08-04 Thread Stephen Coakley

On 08/04/2015 11:36 AM, Ferenc Kovacs wrote:

On Tue, Aug 4, 2015 at 6:12 PM, Terry Cullen te...@terah.com.au wrote:


On Tuesday, 4 August 2015, Johannes Schlüter johan...@schlueters.de
wrote:


On Sun, 2015-08-02 at 17:15 -0500, Stephen Coakley wrote:

You have to admit, NNTP news is an aging technology, with fewer and
fewer readers available as time goes on. Nowadays (for graphical
clients), there's Pan, and Thunderbird, and...? I use Thunderbird at

the

moment, because I didn't want to fill up my email, and there aren't too
many readers. Heck, Thunderbird is technically a discontinued

product.


... and with a forum there is only a single client. The forum
itself. ;-)

SCNR,
johannes



--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Redmine would be a good option.  http://www.redmine.org/

The feature list has most everything covered in this thread.
http://www.redmine.org/projects/redmine/wiki/Features



--




hi,

maybe it just me, but it seems to me, that every time this idea is brought
up, not many people from the actual participants of the list speak up, but
bunch of people who never before sent a mail to the list will chip in.
I'm not saying that there is nothing to improve, but I think that it would
be important to actually incorporate some feedback from the people actually
generating the content on the list.


What can we do to ask feedback on the issue from those people? I really 
want to hear what they think too.



personally I would prefer moving to something like google groups and doing
in a way that we can preserve archives (
https://github.com/wojdyr/fityk/wiki/MigrationToGoogleGroups)
that would allow us to actually kill our ancient list/ezmlm infrastructure
along with news.php.net which would be a huge win.
it would also make it much more easier to search/link to our mailing lists
archives:
news.php.net has no way of searching, news://news.php.net is pretty slow,
we have a couple of mail archives like
https://www.mail-archive.com/internals@lists.php.net/ which are indexing
some of our mailing lists, but they don't have the archives from the
beginings, but I remember seeing a mail from them to ask for our archives
in an mbox and they then would be able to add the missing indexes.
moving to google groups would also make it much easier to manage the groups
(there are less people familiar with ezmlm administration than people with
google groups experience) and make it easier to reply to old mails.

I think that would suit our usage pattern better than a forum and
personally I don't really want to start hosting/maintaining one (we should
have to integrate our own auth and probably acl into that, security audit,
keep it up-to-date, etc.).



I mean really, that would work too and I would be happy with that. That 
offers several advantages as well to the mailing list system. The main 
problem is convincing the group to adopt a platform that is *different* 
than the current one.


--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: Move internals discussion to a better medium

2015-08-04 Thread Stephen Coakley

On 08/04/2015 12:28 PM, Florian Anderiasch wrote:

On 08/03/2015 12:22 AM, Stephen Coakley wrote:


Personally, I'd like to see the mailing list move to a forum-type
system. Lower barrier of entry, more visible archives, and more modern
medium that supports other kinds of attachments and whatnot.



I don't buy the lower barrier of entry argument.

Forum:
- Sign up via web form
- Get authentication email
- click on it, be logged in or not
- post

List:
- Sign up via web form
- Get authentication mail
- reply
- post

Someone iirc said you can even reply without signing up, so it might be
even lower. Unless you're saying people don't know what a mailing list
is or how it works - then ok. The same could be said for any type of
web-based infrastructure.

My actual main gripe with forums is that you can't skim it as easily (if
you're not reading every thread) because everything is split up into
subforums and paginated and whatnot. Or would internals be one subforum?

~Florian



My thought is that no, a number of people don't know what a mailing list 
is (obviously no one in here already), but everyone knows what a forum 
is. The web is everywhere and is taking over the world, whereas mailing 
lists are not. I'm not saying we should jump on the bandwagon, but that 
a forum (or other web-based system) has a lower barrier because people 
already understand that barrier. You are right though, it makes no 
difference to someone who understands neither mailing lists nor forums.


My only real beef with the current system is this:

- Don't mind tons of email - mailing list
- Do mind tons of email - really old news server

Not a problem for those who don't mind tons of email, but if you do, you 
need to get a client for a really old protocol.


--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: Access of protected members

2015-08-03 Thread Stephen Coakley

On 08/03/2015 04:39 AM, Nicolai Scheer wrote:

Hi,

just stumbled upon a strange issue.
I always thought that protected/private member variables can only be
altered from inside the object.

This example shows, that this is not true:

class Test
{
 protected $member = null;

 public static function getObj()
 {
 $myself = new Test();
 $myself-member = hello world;
 return $myself;
 }
}

$new_object = Test::getObj();
var_dump( $new_object );

The output is:
object(Test)#1 (1) {
   [member:protected]=
   string(11) hello world
}

Of course, I'm inside the right class, nevertheless, the object
stored in $myself should not allow direct access to its members.

Is this the expected behaviour? Code of this kind is used quite
frequently for factory methods.

Greetings

Nico



This is correct behavior. This is the same behavior that most 
object-oriented languages have, including Java and C#.


--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Move internals discussion to a better medium

2015-08-03 Thread Stephen Coakley

On 08/03/2015 02:31 AM, Rowan Collins wrote:

On 2 August 2015 23:35:38 GMT+01:00, Marcio Almada marcio.w...@gmail.com 
wrote:

This is their email announce the end of their mailing list back in
2015
https://mail.mozilla.org/pipermail/rust-dev/2015-January/011558.html


Amusingly, the first reply to that is someone trying to set up an email gateway 
to the forum because they like their current workflow...

It's certainly worth considering a forum rather than e-mail if there's real evidence of 
advantages, though. The challenge then would be to figure out what to use - let's not 
pick something trendy and list features like infinite scroll and markdown, 
but actually think about what benefits of the ML we want to preserve, and what we want to 
fix.

So, for starters, we need something with a low barrier to entry, easy to keep 
track of what's new, with good search support, a decent threading and 
sub-threading system... I'm sure we could come up with a shopping list and 
evaluate systems against it.

Regards,



Hmm... there's also this: https://github.com/arkanis/nntp-forum. Not 
sure how much cleanup it would need or what it even looks like. A forum 
interface to the NNTP server. That would make everyone happy... except 
for the people who want to avoid dual interfaces (I think I've heard 
this before...)


--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: Throwable::addSuppressed()

2015-08-02 Thread Stephen Coakley

On 08/02/2015 03:50 AM, Markus Malkusch wrote:

Stephen Coakley:


So what should be the desired behavior, in regard to bug #68270? One
possible behavior would be to, if an exception is thrown inside a
finally block, to attach the uncaught exception from the try block via
the addSupressed() method. The last exception is thrown, and the
exception in the try block is still not lost. Such an alternative could
be bundled with the RFC.


I also like that idea very much that the try-exception is not lost in
this case. So I would agree defining this behaviour can be part of the
RFC as well. Also the current behaviour is nowhere documented so
changing it can be considered as backward compatible (plus it would
close bug #68270).


try {
 try {
 throw new Exception(Exception 1);
 } finally {
 throw new Exception(Exception 2);
 }
} catch (Throwable $e) {
 var_dump($e-getSupressed());
}

we would have $e be exception 2, and $e-getSupressed() return exception 1.


Ack. But the original idea was that Throwable::getSupressed() will
return a *list* of exceptions. You probably didn't change that
intentionally. The try-finally scenario involves only one supressed
exception. I'd like to see a possibility to add more supressed
exceptions, as described in the initial mail for e.g. a use case where
just more resources need to be closed.

Now that try-finally is part of the scope as well, I'd like to add the
case that a supressed exception might be thrown from a catch block as well:

try {
 throw new Exception(Exception 1);

} catch (Exception $e) {
 throw new Exception(Exception 2, 0, $e);

} finally {
 throw new Exception(Exception 3);
}

So in this case the resulting exception would be exception 3, which has
exception 2 as a supressed exception. Exception 1 is as already defined
the previous exception of exception 2.


The more I think about it, the better the idea sounds. Good thought,


Good to hear that the idea finds acceptance. Also I like the evolving of
it. I guess drafting a RFC might be an option then. I will let this idea
brew a bit and then start with that, assuming doing so is fine.

Markus Malkusch



Ah, yes. I didn't realize that was the intention, but 
Throwable::getSupressed() could return an array.


--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: Move internals discussion to a better medium

2015-08-02 Thread Stephen Coakley

On 08/02/2015 07:01 AM, Dor Tchizik wrote:

Hello internals!

I wanted to propose a change to how PHP discussions are made.

Currently, PHP discussions are held on the various mailing lists, managed
by an old mailing list system, without any proper alternative interface to
follow and respond outside of mailing.
The discussion is hidden away, deep within the mails and the archives,
searching is nigh impossible for someone from the outside.
Moreover, subscribing to internals and starting discussion has a *very high
entry bar*, which is bad for any open source project (PHP is still
considered an open source project, yes?). For example, ask a friend to try
and find how to join in on the conversation, without mentioning the mailing
list or the word internals.

I propose that internals discussion to be moved (eventually entirely) to a
different medium, where the example I have in mind is GitHub issues (but
that is up for discussion).


- Every developer worth his salt has a GitHub account. Finding the php
project and looking at the issues is trivial.
- GitHub issues can reference to people by name (triggering an explicit
notification).
- GitHub issues can reference other issues (currently impossible with
the mailing list, unless you link to some archive, and then you can't
really participate in the discussion, nor you have a guaranteed context for
the rest of the discussion)
- GitHub issues can be read and interacted with, from email. (Responding
to an issue/commit comment notification will actually respond to the thread)
- GitHub issues can reference commits directly.
- GitHub commits can reference issues directly.
- You can close GitHub issues.
- GitHub issues are searchable. You have tags.
- GitHub issues can be associated with milestones for easy reference.
- You can comment on specific lines of a commit, and can reference files
and line numbers from issue comments directly.
- You don't need to maintain GitHub, like you do with the current system
- Markdown formatting!

There are probably more advantages I forgot to mention, but any developer
who's familiar with GitHub (or BitBucket, or practically any other form of
Git integration) knows of these free features and advantages, and most of
them use them and take them for granted.

Now, that's not to say the current system has no advantages over the
current one.
A few disadvantages of GitHub:

- GitHub may be down (although I can probably count on one hand how many
times that happened in the past several years)
- GitHub's mailing system is not as robust as the mailing-list software.
People who are exclusively used to emails will have to get used to a
slightly different interface.
- Moving to GitHub (or any other medium) would take some thinking and
work done on the side of the people of internals.

Personally, I think the advantages would seriously overweigh the
disadvantages. PHP would enjoy a more robust discussion system, and a more
open form of discussion, involving more people and more opinions.

(I also have a matching workflow adjustment for the RFC process, but that
can be discussed later)



I made a similar suggestion (of using a new medium of discussion, the 
specifics differ) here: 
https://www.reddit.com/r/PHP/comments/3bxh5h/centralizing_php_discussion_and_communication/ 
and was basically turned down flat.


Personally, I'd like to see the mailing list move to a forum-type 
system. Lower barrier of entry, more visible archives, and more modern 
medium that supports other kinds of attachments and whatnot.


The mailing list has been here for a long time, and it will be an uphill 
battle if you want to have this discussion. I'm sure many people would 
be open to the idea, but many also will not be. I'd love to be proved 
wrong, though.


--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: Move internals discussion to a better medium

2015-08-02 Thread Stephen Coakley

On 08/02/2015 05:31 PM, Rowan Collins wrote:

On 2 August 2015 23:15:12 BST, Stephen Coakley m...@stephencoakley.com wrote:

Heck, Thunderbird is technically a discontinued
product.


  O/T, but to my knowledge Thunderbird is not discontinued, it's just changed 
management because Mozilla are no longer paying for it. The new management are 
actively developing it, but they're probably short of cash...



Oh, my mistake.

Thunderbird works great for reading nested replies and past archives, 
but replying has about a 50% chance of success for me. Oh well.


--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: Move internals discussion to a better medium

2015-08-02 Thread Stephen Coakley

On 08/02/2015 08:29 AM, Rowan Collins wrote:

On 2 August 2015 13:54:46 BST, Niklas Keller m...@kelunik.com wrote:

We're discussing issues here, so what's wrong with an issue tracker?


No, we're discussing every aspect of the project, from release  management to 
personal introductions.


I agree with this, and that's why the GitHub issue tracker doesn't make 
much sense as a mailing list alternative. Not that I'm against the 
GitHub issue tracker -- it would serve better as a replacement to 
http://bugs.php.net, which is a different discussion (and there's not 
really anything wrong with the current bug tracker).


A forum is the correct alternative to a mailing list, if we were looking 
for an alternative.


--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: Move internals discussion to a better medium

2015-08-02 Thread Stephen Coakley

On 08/02/2015 08:17 AM, Markus Malkusch wrote:

Niklas Keller wrote:

2015-08-02 14:32 GMT+02:00 Markus Malkusch mar...@malkusch.de:


What wrong with news://news.php.net/?


That's a joke, right?


No it's not, why should it? You did notice the news:// scheme, did you?


We're discussing issues here, so what's wrong with an issue tracker?


Ok, that's a valid point.


I can see more than one benefit. Probably most important is that you can
follow just some things, instead of getting all the mails. Additionally,
you can ping people


I don't see that point. Newsreader can follow discussions as well. And what
benefit has pinging, compared to a direct email?


Let's reference something then news:e6.64.22108.e69f7...@pb1.pair.com


That's a mailto link for me as well.


Well, that's because you are using a mail client. OP was complaining about
the limited interfaces. Use a Newsreader and there you have your reference.
Even Google is able to follow that.


If you want to build and provide a good search engine around it


I don't, news.php.net is public and search engines for news server do exist.
Google once did search them as well, don't know how it is nowadays though.

Markus Malkusch



You have to admit, NNTP news is an aging technology, with fewer and 
fewer readers available as time goes on. Nowadays (for graphical 
clients), there's Pan, and Thunderbird, and...? I use Thunderbird at the 
moment, because I didn't want to fill up my email, and there aren't too 
many readers. Heck, Thunderbird is technically a discontinued product.


--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Move internals discussion to a better medium

2015-08-02 Thread Stephen Coakley

On 08/02/2015 07:52 AM, Rowan Collins wrote:

On 2 August 2015 13:01:57 BST, Dor Tchizik d...@tchizik.com wrote:

I propose that internals discussion to be moved (eventually entirely)
to a
different medium, where the example I have in mind is GitHub issues
(but
that is up for discussion).


While I think a different medium could be worth considering, I don't think 
squeezing open-ended discussions into an issue management system is a good 
idea. I don't think the archives would be any easier to use, and a lot of 
conversations don't need elaborate code references. Those that do can use Pull 
Requests etc on GitHub already, and we could think of ways of making those more 
visible without generating excessive noise on the main list.

There's always a temptation to put everything in one place, but it generally means 
compromises in the tools used. For instance, Wikipedia and MediaWiki use wiki pages 
for discussion, and Stack Overflow uses QA pages, but neither works as well as 
something actually designed for threaded discussion.

E-mail has the obvious advantage of being usable in many different ways by different 
people. With a decent threaded mail client (i.e. not GMail's web UI, whose 
conversations have no notion of sub-threads or marking some messages as read 
but not others), it's quite easy to pick out the subjects you're interested in, catch up 
after a while away, etc. There may be better archive interfaces out there, as I agree 
that those aren't great right now.

If you still think mailing lists aren't fit for purpose, though, why not look 
at something built for that actual purpose - phpBB, for instance?

As a final note, while encouraging new users is definitely a good thing, any 
project the size of PHP will always have a core set of developers who spend a 
lot of time working on and discussing it. If you make those people's lives 
difficult, no amount of shiny markdown is going to recover their lost effort, 
so any process change has to be carefully considered from that angle.

Regards,



+1. Forums were designed for the specific purpose of threaded 
discussions. I personally am all for switching to a forum system, but I 
know that replacing the mailing list is somewhat controversial.


P.S. I'm really excited for what Flarum http://flarum.org will bring 
when its released. I'd recommend waiting to use Flarum if we were to set 
up a forum. Of course, it's just my preference.


--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Move internals discussion to a better medium

2015-08-02 Thread Stephen Coakley

On 08/02/2015 05:35 PM, Marcio Almada wrote:

I'm not saying that we should do exactly the same thing. PHP is not
Rust. Rust is not PHP. But at least we could stop pretending our
process shouldn't be improved because the walls it offers supposedly
act as a filter for the one who isn't able to get his tools set up
properly. This only shows a deep kind of ignorance on how FOOS works!


Preach it!

Seriously though, I think we should be open to having a discussion about 
replacing the mailing list for internals or for the entire news server. 
If it doesn't happen, then, oh well. It's just a discussion system. On 
the other hand, more modern tools pose more advantages than disadvantages.


I don't think GitHub issues is the right alternative, but I'm glad the 
OP brought the discussion up anyway.


--
Stephen Coakley

--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Move internals discussion to a better medium

2015-08-02 Thread Stephen Coakley

On 08/02/2015 03:34 PM, Rowan Collins wrote:

On Sun, Aug 2, 2015 at 11:04 PM Stig Bakken s...@stigbakken.com wrote:

Are you being serious? Can you provide examples of projects that have
successfully replaced their developer mailing lists with GitHub issues?



On 02/08/2015 21:05, Dor Tchizik wrote:

I already have. iojs (and soon, nodejs), as well as Rust which was
mentioned by someone else.


I don't know about io/node, but Rust most certainly have not replaced a
mailing list with the issue tracker; they've replaced it with a
web-based forum. They use the issue tracker for RFCs, where PHP uses a
mix of wiki and nominated discussion threads, but you started this
thread talking about the discussions, not the RFCs.

Regards,



Yeah, issue tracking isn't really the right thing for daily discussions. 
A forum would be a reasonable alternative to a mailing list, however.


--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: Move internals discussion to a better medium

2015-08-02 Thread Stephen Coakley

On 08/02/2015 02:35 PM, Johannes Schlüter wrote:

Step one: Get a proper mail client. In the mail you sent one can't see
what's from you and what you actually just quoted. All is marked as
quote.
E-Mail is great. It is a push service and I as the receiver can handle
as it matches my work flow. Applying custom filters, highlighters, have
a threaded view or linear.  I also have the discussion while offline
while traveling etc.
There aren't many other system which can handle this amount of
participants and discussions in a good way, especially if we don'T want
to have a lock in of our process on a specific vendor. Switching mailing
list server, if there is any need, is trivial.

johannes

P.S. sorry or this bad full quote


Um, forums work great for that. That's what they're designed for. That's 
not what email is designed for, though it is capable of doing it (hence 
mailing lists were invented).


--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: Move internals discussion to a better medium

2015-08-02 Thread Stephen Coakley

On 08/02/2015 06:40 PM, Lester Caine wrote:

On 02/08/15 23:41, Stephen Coakley wrote:

Thunderbird works great for reading nested replies and past archives,
but replying has about a 50% chance of success for me. Oh well.


I'm up to 24Gb of history over some 20 years and despite attempts by
some developers to mess it up, Thunderbird does the job reasonably well.
I'd prefer to be back on Seamonkey, but that has lost the ability to
handle so big an archive, and in trying to 'keep up' with Firefox and
Thunderbird it's no longer providing what a single suite used to
provide. But then my Linux desktop fills in the gaps so I don't need
Thunderbird to have a bloody calendar or Firefox to muscle in on the
same space. Thunderbird does reliably handle emails in and emails out
without a problem, and I don't need to go on-line to read the traffic,
ore scan the history ...



I don't mean to sound rude, but when have you ever *needed* to access a 
really old message while simultaneously not having Internet access? I 
just can't imagine needing to do such a thing. Not saying it's wrong for 
you to do so.


--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: Move internals discussion to a better medium

2015-08-02 Thread Stephen Coakley

On 08/02/2015 06:31 PM, Lester Caine wrote:

On 03/08/15 00:01, Markus Malkusch wrote:

Anyways, OP was complaining about missing interfaces and features, which is
simply not true. You can communicate through Email, NNTP and if one wants a
webinterface so hardly just wrap one around NNTP. How can it be more
accessible by reducing it to some webinterface only?


No one said that it would be a web interface only (though that is most 
common). An email system could be supported.


I hate sounding like a hipster youngin', but there's a reason why web 
interfaces have been replacing a lot of things over the years, though. 
It seems like pretty much everything computerized can access a web 
interface these days.



Some of the web based forums have attempted to integrate email with the
on-line interface. Yahoo groups is an utter pain but I don't have to use
any of the web based interface, I just use emails and in the morning
there will be a number sitting in inbox so I don't have to scan around a
dozen sites to see what is happening.


That does seem like a reasonable advantage to supporting email.


The ones that do send email
notifications make a half hearted attempt, but one has to go on line to
see the content o post replies. What *IS* needed is a nice cross format
system of working, but that only requires adding a preferred web
interface to the existing email service? Perhaps then people who seem to
prefer top posting will use the web interface and those of us who prefer
a private local archive will then simply get the new text ... as an email.


That sounds like a conflict of interest, but that's just me.


There are already web based interfaces but not providing what some
people seem to want. What is stopping the development of one of those
interfaces into an addition to the existing email channels? No need to
MOVE anything!



What is stopping development? NNTP is an ancient protocol. Nobody wants 
to bother writing *new* software for it.


--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: Throwable::addSuppressed()

2015-08-01 Thread Stephen Coakley

On 08/01/2015 09:44 AM, Markus Malkusch wrote:

Christoph Becker:

Markus Malkusch wrote:


I'd like to revise that. I'd just learned that finally does indeed fit
here, as it would automatically glue exceptions:


[..]


Note that there's an open bug report (https://bugs.php.net/68270)
regarding this issue.


Thank you for pointing to that bug. So I understand the authors of that
bug are surprised that finally does magically attach exceptions. I did
actually also not expect that, as it is not documented nor do I have
that experience from other languages (did only check with Java).

So I can assume that magic finally glue behaviour is not considered
stable, which then again gives Throwable::addSupressed() IMO a
justification.

Markus Malkusch



So what should be the desired behavior, in regard to bug #68270? One 
possible behavior would be to, if an exception is thrown inside a 
finally block, to attach the uncaught exception from the try block via 
the addSupressed() method. The last exception is thrown, and the 
exception in the try block is still not lost. Such an alternative could 
be bundled with the RFC.


The alternative s to just drop the exception, never to be seen again. 
This is the behavior in both Java and C#. Python has a different 
approach. Python has two properties that contain previous exceptions: 
__context__, which holds implicitly chained exceptions, and __cause__, 
which holds explicitly chained exceptions. This system makes a ton of 
sense, and I think PHP exceptions should distinguish between the two as 
well.


(Relevant PEP: https://www.python.org/dev/peps/pep-3134/)

Currently, in the try/finally situation described, $previous is used to 
hold the missing exception. $previous should only hold explicitly passed 
exceptions, as described in the docs. addSupressed() could be defined as 
for implicit chained exceptions. The method could be paired with a 
Throwable::getSupressed() to retrieve the implicitly added exception.


So in a case like this:

try {
try {
throw new Exception(Exception 1);
} finally {
throw new Exception(Exception 2);
}
} catch (Throwable $e) {
var_dump($e-getSupressed());
}

we would have $e be exception 2, and $e-getSupressed() return exception 1.

The more I think about it, the better the idea sounds. Good thought, Markus!

--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: Throwable::addSuppressed()

2015-08-01 Thread Stephen Coakley

On 08/01/2015 09:44 AM, Markus Malkusch wrote:

Christoph Becker:

Markus Malkusch wrote:


I'd like to revise that. I'd just learned that finally does indeed fit
here, as it would automatically glue exceptions:


[..]


Note that there's an open bug report (https://bugs.php.net/68270)
regarding this issue.


Thank you for pointing to that bug. So I understand the authors of that
bug are surprised that finally does magically attach exceptions. I did
actually also not expect that, as it is not documented nor do I have
that experience from other languages (did only check with Java).

So I can assume that magic finally glue behaviour is not considered
stable, which then again gives Throwable::addSupressed() IMO a
justification.

Markus Malkusch



In that case, an addSupressed() method still makes sense, and is once 
again a good idea. The finally block bug should be fixed before stable 
release, too, I think.


--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: Throwable::addSuppressed()

2015-07-31 Thread Stephen Coakley

On 07/31/2015 08:25 PM, Markus Malkusch wrote:

Stephen Coakley:


Interesting thought, but how is this different than including a previous
throwable and throwing a new, more descriptive exception?

} catch (Exception $e1) {
  try {
  $resource-close();
  } catch (ResourceException $e2) {
  // Pass in $e2 as the previous exception in the chain.
  throw new ResourceFailedException($e1-getMessage(),
$e1-getCode(), $e2);
  }
}


Sorry, in my previous mail I actually forgot to answer your question.
What you suggest is a common pattern to work around the lack of
Throwable::addSupressed(). There are two big differences:

1) There's no causality between e1 and e2. You pass the message from e1
to the newly created ResourceFailedException which is caused by e2.
Actually the causality here is correct, as ResourceFailedException is
caused by e2. But what I understand is that ResourceFailedException
should substitute e1 and e1 is not caused by e2. Just imagine e1 has the
message insufficient funds. Then the user gets an exception which says
insufficient funds is caused by could not rollback transaction.

2) You are loosing one stack trace (in this case from e1). For me the
stack trace is the most important information in the exception. In this
use case there are two stack traces and I want to have both of them.

And then again this is just a simple example scenario with one resource.
There might exist n resources.

Markus Malkusch



That makes sense -- I can see the uses for that. I don't mean to play 
devil's advocate, but is it worth sacrificing the immutability of 
exceptions for an addSupressed() method? Other than that, I think I 
would be for such an addition.


--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: Serializing exceptions

2015-07-31 Thread Stephen Coakley

Hi!


week or two and I serialize exceptions (excluding stack trace arguments)
to send them back to the calling process to aid in debugging process
failures.


But then you don't need to serialize Exception. You need to send the
text representation of Exception, for humans to look at, not the live
Exception object. Sending the actual object would be next to impossible
anyway (i.e. how you send over the live DB connection on DB query
exception?).



But the text representation includes the exception message, code, and 
the stack trace. That's pretty much the whole thing. But you are right, 
I don't want (and couldn't transfer) the live objects related to the 
stack trace, if that's what you're referring to. That's why I would omit 
the arguments in each stack trace item during serialization, because who 
knows what it could be.


I just think that serializing exceptions is a buggy feature right now, 
and we should fix the feature instead of throwing it out.


--
Stephen Coakley


--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: Exposing object handles to userland

2015-07-31 Thread Stephen Coakley

On 07/31/2015 09:23 AM, Julien Pauli wrote:

Hi people.

I've been pinged many times to add a new spl_object_id() function to PHP,
that would return the internal object handle of an object.

Today, spl_object_hash() partially allows that, but adds many randomness to
the result, which is not very cool to use later  (why does it even add
randomness ?).

There has been topics about this subject.
For example, at http://marc.info/?l=php-internalsm=141814350920452w=2


Beeing able to get the object handle back in PHP userland would ease many
tools, mainly debug-oriented tools.
I know PHPUnit, Symfony and many big projects today make use of
spl_object_hash() to identify objects.

I also know people that print_r($an_object) and parse the output just to
extract the object handle from there... Crazy isn't it ?
Why couldn't we help those people by simply adding a new function that does
the job ?

Thoughts ?


Julien.Pauli



I can think of several use cases why this might be useful, and not just 
for debugging-related code. It could be used for indexing some sort of 
complex object storage data structure (if you can't/won't use 
SplObjectStorage). I can think of a few libraries that us 
spl_object_hash() to do the same thing but doesn't work well in 
conjunction with forking (probably due to the randomness factor).


+1

--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Re: Serializing exceptions

2015-07-31 Thread Stephen Coakley

On 07/28/2015 03:46 PM, Stanislav Malyshev wrote:

Hi!


This sort of change would be a major BC break for 8.x or similar.


How is it a major BC break? You make it sound like serializing
exceptions is something no application can do without. I have yet to see
a single case where it's useful (yes, I've read the Symphony comment but
I'm not sure why they're doing it and if it's indeed something that
should be done and not an ugly hack like unserializing fake internal
objects).


I also don't see security implications, tbh.


I don't want to discuss it in detail yet, but check out currently open
or recently fixed security issues and see how many of them relate to
serialized exceptions and consequences of that.
--
Stas Malyshev
smalys...@gmail.com



Serializing exceptions can be useful in parallel code using multiple 
processes or threads. I have been working on a concurrency library for a 
week or two and I serialize exceptions (excluding stack trace arguments) 
to send them back to the calling process to aid in debugging process 
failures.


I agree there aren't too many use cases, but there are a few. Of course, 
exceptions aren't *consistently* serializable, which is still a problem 
that should be resolved in some way.


--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: Serializing exceptions

2015-07-31 Thread Stephen Coakley

On 07/27/2015 02:08 AM, Stas Malyshev wrote:

Hi!

Looking into some issue, I've discovered that, to my surprise,

Exceptions are serializable. Except that it doesn't always work of
course (e.g. see http://stackoverflow.com/q/9747813/214196) because
exceptions contain backtraces, and those can contain non-serializable
objects. So in reality, you never know if you can serialize it or not.

So, I wonder - would it be ok to make exceptions not serializable at
all? I think that would prevent major WTF factor when people try it and
it randomly fails.



Since discussion on this did not lead to a definite conclusion, but I did
not hear from anybody that they need serialized exceptions, and we keep
getting bug reports about exception serialization and various issues
triggered by it, I propose this change:
https://github.com/php/php-src/pull/1442

Since it is kind of BC break (even though I assume it breaks something that
needed not to be allowed in the first place) I'd like to merge it in 7.0.0.
Please object if you think this should not be done and explain why.
Otherwise I intend to merge it after a suitable wait and after adding
necessary tests/docs.

Thanks,



I'm serializing exceptions in a current project, and I would much prefer 
losing `args` (the only part not always serializable) from the trace 
than not being able to serialize the exception at all.


Making exceptions not serializable will just result in another userland 
wrapper, like a SuperException, that lets you serialize and unserialize 
with eval()'s. I think allowing the serialize to drop args in the trace 
and just include a warning in the docs about the serialization being lossy.


My 2 cents.

--
Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: Throwable::addSuppressed()

2015-07-31 Thread Stephen Coakley

On 07/28/2015 04:51 PM, Markus Malkusch wrote:

Hi PHP

So I read that there's this Throwable interface coming. Great! How about
extending it with one further method:

void Throwable::addSuppressed(Throwable exception)

Semantic is the same as Java's Throwable.addSuppressed()¹.

Why? Well consider a code fragment which wants to close a resource
during an exception:

} catch (Exception $e1) {
 try {
 $resource-close();
 throw $e1;

 } catch (ResourceException $e2) {
 // The information about $e2 is lost.
 throw $e1;
 }
}

Currently PHP has no method to propagate both $e1 and $e2. With
Throwable::addSuppressed() $e2 could be added as a suppressed exception
to $e1:

} catch (Exception $e1) {
 try {
 $resource-close();

 } catch (ResourceException $e2) {
 e1-addSuppressed($e2);

 }
 throw $e1;
}

To make this information useful (for e.g. a logger) there's one further
method needed:

Throwable[] Throwable::getSuppressed()

So PHP, what do you think, might a RFC find acceptance?

Best wishes
Markus Malkusch

[1]:
http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html#addSuppressed-java.lang.Throwable-



Interesting thought, but how is this different than including a previous 
throwable and throwing a new, more descriptive exception?


} catch (Exception $e1) {
 try {
 $resource-close();
 } catch (ResourceException $e2) {
 // Pass in $e2 as the previous exception in the chain.
 throw new ResourceFailedException($e1-getMessage(), 
$e1-getCode(), $e2);

 }
}

What you're describing doesn't seem like a common use case.

Also, this is pretty nitpicky, but the above code might fit better with 
a finally block when closing resources:


try {
// Do something with $resource here...
} finally {
 $resource-close();
}

-- Stephen Coakley

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Re: Output, parameter

2015-06-18 Thread Stephen Coakley

On 06/18/2015 11:12 AM, Dominic Grostate wrote:

A feature I'd quite like to see is something similar to C# out arguments.
Which is an argument provided empty to a function (or with a value to be
ignored) that the function must write to before returning.

Normally this wouldn't be necessary since you can do this anyway by passing
by reference, however I would like to make the same case for it that was
made for return types.

A possible syntax to differ from C# might be:

function read(string ^$bytes, int length): int
{

}

The arrow indicating that a value will be written to the argument.

Another case for this is the fact it is unfeasible to provide a type hint
for reference arguments because if the provided var is null or newly
created it will throw an error.

Using type hints on outputs will both validate that the populating value is
of the correct type, as well as provide popular IDEs a hint to what the
type has changed to.

Thanks,
Dominic


I don't see this being useful enough for adding a new syntax. I always 
thought that out params in C-family languages was a hack and should be 
avoided if possible. Newer C++ libraries tend to return tuples instead, 
don't they? Most of the time people just return an array of values in 
PHP code I've seen.


--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php