Re: [PHP-DEV] generating code from AST

2017-03-08 Thread Nikita Nefedov

> On 8 Mar 2017, at 08:49, Sebastian Bergmann  wrote:
> 
> Am 07.03.2017 um 11:33 schrieb Derick Rethans:
>> Because installing an extension is too hard?
> 
> No. To ensure that userland functionality that is based on compiler
> internals (token stream, abstract syntax tree, bytecode) does not fall out
> of sync with the compiler.
> 
> We already have an extension that is built-in and enabled-by-default for
> the token stream. Why not have one for the abstract syntax tree and
> bytecode representations?

To be honest, that’s exactly what we might want to avoid. Last time someone 
wanted to do actual improvements to our lexing they were stopped because 
changing tokens would mean breaking code that relies on `token_get_all()` which 
is a core extension user land function.

It might be though that it’s only the problem with lexing and it should not be 
a problem for AST because it is, ahem, abstract.
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] [RFC][Discuss] Arrow Functions

2017-01-31 Thread Nikita Nefedov

On Mon, 30 Jan 2017 20:55:07 +0300, Levi Morrison  wrote:


Bob Weinand and I are happy to announce that the [Arrow Functions][1]
RFC is moving into the public discussion phase. We have been
collaborating on this RFC for many months now and finally have a
proposal we are happy to discuss in the open.

Here is an example of an existing closure:

function ($x) use ($arr) {
return $arr[$x];
}

This RFC proposes syntax and semantics to simplify this common usage to:

fn($x) => $arr[$x]

More details are in the RFC. The [implementation][2] currently has no
known issues and is ready for you to download, build and test, which
we encourage you to do.

We look forward to a productive discussion period and are happy to
answer questions.

For historical purposes, the revision of this RFC is currently at
[1485798604][3].

  [1]: https://wiki.php.net/rfc/arrow_functions
  [2]: https://github.com/morrisonlevi/php-src/tree/arrow_functions
  [3]: https://wiki.php.net/rfc/arrow_functions?rev=1485798604


Hey Levi, Bob,

that looks very good.

The fn prefix is peculiar yes but it's alright, it doesn't harm neither
readability nor writability, it even has some precedences in other
languages (think Rust, Elixir) and as we all know it is necessary for
parser.

Thanks for the work, I hope it lands in PHP.

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



Re: [PHP-DEV] Not autoloading functions

2017-01-27 Thread Nikita Nefedov
On Fri, 20 Jan 2017 10:04:44 +0300, Rasmus Schultz   
wrote:



Just a quick thought.

Since the autoloading functions proposal is stalled, how about allowing  
for

import of static functions instead?

use function Foo::bar;

bar(); // calls Foo::bar()

There are two benefits to this approach:

1. There is immediate support for autoloading without any need for  
adoption

or support in existing autoloaders.

2. Pseudo-namespaces (abstract classes with stateless static functions)  
are
already widely practiced in PHP - a lot of existing code would be  
supported

as is.

The syntax when calling functions would be the same.

If we had function autoloading, we would likely collect related functions
in a file anyway - putting them in a class instead gives more less the  
same

exact result.

The only drawback I can see, is the inability to import a whole set of
functions with one statement - but being explicit about external imports  
is
widely considered best practice for classes and interfaces, so why not  
for

functions. Yeah, it's a bit inconvenient, but at least we can move ahead
and leverage existing code without changes or BC breaks. It's not all  
bad.

It's better than nothing perhaps? :-)

Thoughts?


Maybe we might think about modules this time?
Lots of languages use this approach and they seem to be pretty happy
with it.

Here's how it could look like, very abstractly. I don't really see
any big issues with the way how to implement it either.

https://gist.github.com/nikita2206/2e4ab1b314e840f93ed75a0b88266d35

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



Re: [PHP-DEV] Class Constant Finalization

2017-01-24 Thread Nikita Nefedov


> On 25 Jan 2017, at 09:48, Scott Arciszewski  wrote:
> 
> All,
> 
> Given that we can now declare a class constant as public, protected, or
> private, can we also declare them final in 7.2?
> 
> https://3v4l.org/rJG0V
> 
> Ideally, this code would error on line 18 rather than 15.
> 
> Scott Arciszewski
> Chief Development Officer
> Paragon Initiative Enterprises 

In my book, ideally, there would be no class constant inheritance as inherited 
constants don't really make sense when they are known at compile time. People 
often use this feature in order to get things like this to work:

class LibLevelClass {
const FOO = "default";
public function doSomething() {
echo "the value of FOO is: " . static::FOO;
}
}

class ExtensionClass {
const FOO = "custom";
}

But this approach is error prone due to untyped nature of constants (one could 
override the constant with an array value). In the end this inheritance is 
always unnecessary.


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



Re: [PHP-DEV] Change in type-hint representation

2017-01-11 Thread Nikita Nefedov


> On 11 Jan 2017, at 19:37, Dmitry Stogov  wrote:
> 
> The patch was updated according to feedback: added comments, better names and 
> encapsulation, less magic, better code reuse, keep a free bit in zend_type 
> for future extension.
> 
> 
> 
> 
> 
> https://gist.github.com/dstogov/1b25079856afccf0d69f77d499cb0ab1
> 
> 
> Thanks. Dmitry.

Thanks for the patch, looks good to me!
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Change in type-hint representation

2017-01-11 Thread Nikita Nefedov
On Wed, 11 Jan 2017 16:51:22 +0300, Michał Brzuchalski  
<mic...@brzuchalski.com> wrote:





2017-01-11 14:35 GMT+01:00 Nikita Nefedov <inefe...@gmail.com>:

-- snip --


 [   ]    xxy0 - for IS_OBJECT type hint

   where the ``s are a (zend_string *) pointer and `y` designates

   an allow_null flag




I've got prepared Object Typehint RFC  
https://wiki.php.net/rfc/object-typehint where
IS_OBJECT is used without class name as type hint for any object kind,  
if this patch

would be applied how can I deal with this new zend_type?
As far as I undestand last 0 for IS_OBJECT and no (zend_string *)  
pointer would give me
empty zend_string value right? So that won't bive me any chances to  
store IS_OBJECT

without classname am I right?


Hey Michal,

no for you it's quite easy, you can just store IS_OBJECT with

ZEND_TYPE_ENCODE_HINT(IS_OBJECT, is_null)

But then the code that checks ZEND_TYPE_IS_CLASS will need to
be adjusted to work with

ZEND_TYPE_IS_HINT(type) == 1 && ZEND_TYPE_HINT(type) == IS_OBJECT

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



Re: [PHP-DEV] Change in type-hint representation

2017-01-11 Thread Nikita Nefedov

On Wed, 11 Jan 2017 15:07:39 +0300, Dmitry Stogov  wrote:


Hi,


I propose to introduce a unified type representation (zend_type).

Now it's going to be used for typing of arguments and return values.

Later we should use it for properties and other things.


https://gist.github.com/dstogov/1b25079856afccf0d69f77d499cb0ab1


The main changes are in zend_types.h and zend_compile.h, the rest is  
just an adoption for new type representation.


I don't think we need RFC, because this is just an internal change that  
doesn't change behavior.



I got the idea working on typed properties together with Bob and Joe.

https://github.com/php/php-src/compare/master...bwoebi:typed_ref_properties

I think it would be better to introduce zend_type and then continue work  
on typed properties.



Any comments?


Thanks. Dmitry.




Hey Dmitry,

Having worked on callable prototypes I'd say unifying PHP types in Zend
is something we urgently need for PHP to continue evolving.

I'm not sure if PHP have ever been compatible with less-than-32bit
archs but if it was I think it should be said that this would break
such compatibility though.

It would be great if there were some comment in the code near zend_type
declaration where you'd explain how it is used and how additional
data is being added to the pointer.

Is there any use of ZEND_TYPE_CE() macro? It seems to be forgotten there?

If I understood this correctly, the layout of zend_type is as follows:

  [   ]    xxy0 - for IS_OBJECT type hint
where the ``s are a (zend_string *) pointer and `y` designates
an allow_null flag

  [   ]    xxy1 - for all other type hints
where the ``s are a IS_CALLABLE, _IS_BOOL, IS_LONG, IS_DOUBLE,
IS_STRING or IS_ARRAY

Do we decide here that IS_REF modifier should belong to the concrete
usages of the type (e.g. referentiality is a property of a variable
and not of a type)?
I'm not sure this if is a right decision or not but I feel like this
question should be raised. It is usually the opposite in other languages.

How would you plan to extend this further? Let's say at some point we
will have callable prototypes or generic classes: we will need to encode
somehow this type into zend_type: `callable(A)` or `A`.
Even right now it might be useful (as you suggest with ZEND_TYPE_CE)
to store a (zend_class_entry *) instead of (zend_string *) when
it is known to us in the zend_type.
Seems like without extending zend_type to the size of two pointers
it almost isn't doable :\
Or, it could be made that zend_type, when it's not a simple type hint,
would point to the `zend_type_complex` which would store a
zend_class_entry pointer (or not, if it's for callable) and an array
of type specifiers. But that introduces another indirection.

Anyway thanks for polishing this part, we definitely need zend_type in  
some form.


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



Re: [PHP-DEV] Re: number_format() = "-0.00"

2016-11-25 Thread Nikita Nefedov
> On 25 Nov 2016, at 21:07, David Rodrigues  wrote:
> 
> As reference, I'll put here what some languages does on this case:
> 
> Java:-0.00   (http://ideone.com/NOxen1)
> Python:  -0.00   (http://ideone.com/llxGHA)
> Ruby:-0.00   (http://ideone.com/j3KgMd)
> C++14:   -0.00   (http://ideone.com/P3WdoJ)
> Node.js: -0.00   (http://ideone.com/31gQgV - v0.12)
> 
> C#:   0.00   (http://ideone.com/vW0F0b)

Hey,

You're comparing printf with number_format here. Even though both are 
formatting functions they're not necessary of the same domain. (you can't 
really do what number_format does with just a printf in a sane way (technically 
you can, but that depends on the locale and if you were to change locale just 
to choose another separator that would be a bad idea))


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



Re: [PHP-DEV] number_format() = "-0.00"

2016-11-25 Thread Nikita Nefedov
On Fri, 25 Nov 2016 11:10:47 +0300, Rasmus Lerdorf   
wrote:



On Thu, Nov 24, 2016 at 11:54 PM, Craig Duncan  wrote:

I've submit a PR (https://github.com/php/php-src/pull/2220) to fix a  
bug (

https://bugs.php.net/bug.php?id=73581).

Kalle suggested I run the change by here to see if there are any  
concerns

or feedback about merging this?



This doesn't seem like a bug to me. Our floating point is all IEEE 754  
and

as per IEEE 754 -0.00 is the correct and expected result here.

-Rasmus


I'm afraid majority of people (myself included) see number_format
and money_format not as a IEEE 754-accurate float value rendering  
functions.


Instead people use them for printing human-readable numbers, which
usually excludes implementation quirks such as negative zero or
`2.0` represented as `1.999~`.

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



Re: [PHP-DEV] DateTime microseconds discussion

2016-11-08 Thread Nikita Nefedov

Hey Arjen,

On 8 November 2016 at 09:32, Arjen Schol  wrote:

There is no easy way to set microseconds to 0, you have to call setTime


There actually is an easy way, you can pass microseconds absolute value
in the constructor as well, it would like: `new DateTime("5 minutes ago, 0  
microseconds")`


As Dan said it is probably a mistkae in the code, really, and it is a very  
popular one,
to think that `new DateTime("5 minutes ago") == new DateTime("5 minutes  
ago")`.

If you sample it enough times even on pre-7 versions of PHP you will get
inequality as well: https://3v4l.org/JV59e (sorry for overloading 3v4l a  
bit here).
It is especially an undesirable mistake because it causes failures  
randomly,

no one likes their test suite failing /sometimes/, it makes debugging
a very unpleasant experience.

When doing date manipulations, let's say the task is to generate a report  
for the
previous month, you need to always have a base date as a point of  
reference:


```
$startDate = new DateTimeImmutable("first day of previous month,  
00:00:00.0");

$endDate = $startDate->add(new DateInterval("P1M"));
```

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



Re: [PHP-DEV] OpenSSL - New Defaults

2016-11-07 Thread Nikita Nefedov


> On 7 Nov 2016, at 03:35, Scott Arciszewski  wrote:
> 
>> On Sun, Nov 6, 2016 at 2:19 PM, Jakub Zelenka  wrote:
>> Hi,
>> 
>> On Thu, Nov 3, 2016 at 4:11 PM, Scott Arciszewski 
>> wrote:
>>> 
>>> Hi,
>>> 
>>> Can we change openssl_public_encrypt() and openssl_private_decrypt() from
>>> defaulting to PKCS1v1.5 padding, in favor of defaulting to OAEP?
>>> 
>>> I'll create an RFC for this later. It will just prevent a lot of issues.
>>> 
>>> To wit:
>>> 
>>> - https://framework.zend.com/security/advisory/ZF2015-10
>>> -
>>> 
>>> https://github.com/garyr/portunus/blob/89853c180c85c71baac7015cb77ff8ddae129942/src/Portunus/Crypt/RSA/PrivateKey.php#L20
>>> -
>>> 
>>> https://github.com/NorseBlue/Sikker/blob/c158bab1e676d751e5228cb17ecf9593c6b94e95/src/Asymmetric/Keys/PrivateKey.php#L72
>>> 
>>> If we can't stop PHP developers who aren't cryptographers from writing
>>> their own high-level RSA implementation, we can at least make it safer by
>>> default.
>>> 
>> 
>> We can't change default in 7.x as it would be a BC break and in this case a
>> very hard to catch BC break as the only way how we could let user know about
>> that is a documentation. This is a very low level function and PKCSv1.5 is
>> still used a lot so some apps might depend on. I think that the default is
>> bad but I don't think that breaking both function without notice is a good
>> solution as users might not be able to catch it especially if it's some
>> third party protocol that is not very secure but you don't have choice
>> because 3rd party won't change it (that was actually the only case where I
>> used these functions in practice so it's not made up). And even worse if you
>> don't have tests, then it breaks just production without a warning...
>> 
>> What I would prefer instead is to deprecate calling
>> openssl_(private|public)_(en|de)crypt without a padding parameter. The
>> default would stay the same but user would get a deprecation message and the
>> parameter would become required in PHP 8. We should add a note to the doc,
>> to let the user know what the safest option is. It means OAEP for
>> openssl_private_decrypt and openssl_public_encrypt. In case of
>> openssl_public_decrypt and openssl_private_encrypt, we support just
>> PKCS1v1.5 but if we add support for PSS (would require a little bit of
>> tweaking as it works on EVP level only but might add it later), we could
>> easily recommend it then.
>> 
>> I have got actually very similar plan for openssl_seal and openssl_open that
>> have default method rc4. Again very bad default but the best way how to let
>> user know is to deprecate it rather than choose new default and break
>> compatibility.
>> 
>> Cheers
>> 
>> Jakub
>> 
>> 
> 
> Hi Jakub,
> 
>> We can't change default in 7.x as it would be a BC break and in this case a 
>> very hard to catch BC break as the only way how we could let user know about 
>> that is a documentation.
> 
> A sane proposal had emerged before I even received this email, via
> kemmeta on Reddit:
> 
> https://www.reddit.com/r/PHP/comments/5axmn5/phpinternals_openssl_new_defaults_proposal/d9kx8sa/?context=1
> 
> A backwards-compatible interface would default
> openssl_public_encrypt() to OAEP, but openssl_private_decrypt() would
> default to a new constant: OPENSSL_PKCS1_UNSPECIFIED, which when
> passed would first try OAEP and, if a padding error occurred, emit an
> E_DEPRECATED and fallback to PKCS1v1.5 (a.k.a. "let's pretend Daniel
> Bleichenbacher's research doesn't exist" mode).
> 
> The upside is that better security would be applied opportunistically
> in codebases where the PHP developer was not a cryptographer. The
> downside is a performance hit unless you specify one mode or another.
> 
> A long term solution would be to not even use RSA anymore.
> 
>> I have got actually very similar plan for openssl_seal and openssl_open that
>> have default method rc4. Again very bad default but the best way how to let
>> user know is to deprecate it rather than choose new default and break
>> compatibility.
> 
> If your plan is to get it more in line with libsodium's
> crypto_box_seal API, I'd love to see it.
> 
> Scott Arciszewski
> Chief Development Officer
> Paragon Initiative Enterprises
> 
> -- 
> PHP Internals - PHP Runtime Development Mailing List
> To unsubscribe, visit: http://www.php.net/unsub.php
> 


Hey,

It might make even more sense to not provide a default here at all. As history 
shows that those methods that are considered secure today can become 
less-than-desirably secure in a couple of years. Which means the same cycle of 
deprecation/changing defaults in years to come.
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] Statically verifiable callables

2016-06-21 Thread Nikita Nefedov

Morning internals,

I would like to gather some reactions on the proposal to add
a 'statically verifiable callable as a closure language construct'.

That would be functionally similar to the recently added
Closure::fromCallable() with the exception being statically
verified by IDEs or precompilers/linters/code inspection tools.

Right now it is absolutely context-dependent guess whether
`[$obj, 'foo']` is a reference to a method `foo` of `$obj`
or something completely different. This makes code analysis and
refactoring very hard when it comes to using methods/functions
as callables passed somewhere.

What I'm proposing is to add a language construct, the usage of
which would look similar to this:

function bar() {}
class Foo { function dyn(){} static function stat(){} }

callable(Foo::stat);

callable((new Foo)->dyn);

callable(bar);

callable() construct would return a Closure instance, just like
Closure::fromCallable() does but without the overhead of parsing
the array and with all function/class identifiers being T_STRINGs
rather than string literals.

The main advantage for me personally will be IDEs being able to
implement refactoring and code highlighting (=> more readable)
features on top of this (e.g. rename method can also rename all
accesses to this method but not when it's a string literal).

I'm aware that people might not like the fact that with this
syntax method access looks completely the same to the
field access and can be misleading for novices or can harm
readability of the code. If someone has better ideas we can
all share them here.

The patch should be pretty simple, here for example are the
parser changes I made to make sure this syntax is possible:

https://gist.github.com/nikita2206/bf419c8c23479bbf826c31cffe16a749

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



[PHP-DEV] Re: [RFC] [Vote] Callable types (now: Callable prototypes)

2016-06-06 Thread Nikita Nefedov

Evening internals,

The vote for Callable prototypes has been declined with 18 votes in favor  
and 19 against adding the feature.


Thanks everyone for participating, we will work on problems raised in the  
discussion and see if it meets people's expectations in 7.2


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



Re: [PHP-DEV] can't reflection on DateTime properties?

2016-06-04 Thread Nikita Nefedov
On Sat, 04 Jun 2016 22:36:19 +0300, Rasmus Schultz   
wrote:


I wrote a library that can serialize/unserialize PHP object graphs to  
JSON

data.

Somebody reported it doesn't work on the DateTime class.

Does this deliberately not work?

$date = new DateTime();

var_dump($date);

outputs:

object(DateTime)#1 (3) {
  ["date"]=>
  string(19) "2016-06-04 19:30:19"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}

however, this...

$reflection = new ReflectionClass('DateTime');

var_dump($reflection->getProperties());

outputs:

array(0) {
}

The object clearly has properties corresponding to it's internal state,  
but

reflection doesn't seem to report them?

Also, what comes out of var_dump() appears to be something intended for
human consumption? I'm guessing that's not the actual internal state of  
the
object - most likely the internal state consists of the "timezone_type"  
and

an integer timestamp?


Yes, DateTime/DateTimeImmutable classes define custom `get_properties`  
zend_class_entry handler:  
http://lxr.php.net/xref/PHP_MASTER/ext/date/php_date.c#2162
Which is called whenever you `var_dump()` it or foreach over the object or  
call a `get_object_vars()` on it: https://3v4l.org/tNJXN


But reflection on the other hand directly uses  
`zend_class_entry->properties_info` table which DateTime does not have:  
http://lxr.php.net/xref/PHP_MASTER/ext/reflection/php_reflection.c#4574


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



Re: [PHP-DEV] [RFC] [Vote] Callable types (now: Callable prototypes)

2016-05-24 Thread Nikita Nefedov
On Tue, 24 May 2016 02:24:12 +0300, Dan Ackroyd <dan...@basereality.com>  
wrote:



Hi Nikita,

On 23 May 2016 at 15:27, Nikita Nefedov <inefe...@gmail.com> wrote:

With this message I'd like to go to vote
with the Callable prototypes RFC targeted at 7.1:
https://wiki.php.net/rfc/callable-types


To explain my vote - I think we definitely need to be able to specify
the signatures of callables in PHP, and I would very probably support
either a 'typedef' RFC, or an expansion of current functional type
(i.e. invokables) to be easier to use with functions, but I just
couldn't possibly vote for an RFC that means people would sometimes
write code similar to this:

function foo(int $a, int $b,
callable(callable(callable(callable(int, int):int $zebranky, int):int
$pik, int):int $fot, int):int $zot): int {
return $zot($a, $b);
}

to use the feature of the RFC.

I realise that is an extreme case, but I think that splitting where a
type is defined (with a name) and the place where it is used to be
separate places, is one of the things that the design of PHP got
right. It makes it easier to read code, even if it makes the language
feel less 'powerful' than other languages.

cheers
Dan


Morning Dan,

I think we definitely would need type aliases. But I also hoped for
union types to get in, so that after these two we could have another RFC
that would do typedefs for callables and for unions.

Doing typedefs for callables only seems too narrow. People would
probably vote 'no' for that RFC because apart from creating new syntax for
callables it would also create a flavour of typedef that works in limited
scope only. And that seems completely fair, typedef is another feature.

And even with typedefs I see no reason not to support inline callable  
prots.

Do you remember 'Arbitrary expressions' RFC? I look at it just like at
expressions, and I think there's a need for any possible type to be
expressed directly in a parameter typehint. Making code more readable
would be a responsibility of a user who would decide whether he needs
to use function signatures or not.

Regarding Joe's functional interfaces, I wish they were passing vote.
They can be a nice addition (and a pretty simple one) to the language.
I also think they are not related to this RFC, as their usage is completely
different... What I am aiming at with this (and possibly next) RFC is
to make function composition work better and functional interfaces don't
touch this subject at all. The fact that function needs to opt-in and
the fact that the signature of a function needs to be completely
same as in interface (so no variance) makes it useless in cases
where callable prototypes should be used instead.


I realise that is an extreme case, but I think that splitting where a
type is defined (with a name) and the place where it is used to be
separate places


I think so too but "callable(int): int" is not defining a type, it is
using it. On the other hand "callable" here is a type constructor.
If we would have generics of some form this would be similar to:
"Function<int, int>" where you don't define a type but you create it
passing "int, int" arguments to a type constructor (or a template,
or a generic class) which results in a type in the end. When you
get parametrized types there's a natural need for parameterizing
them in place...

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



Re: [PHP-DEV] [RFC] [Vote] Callable types (now: Callable prototypes)

2016-05-24 Thread Nikita Nefedov
On Mon, 23 May 2016 22:59:10 +0300, Markus Fischer <mar...@fischer.name>  
wrote:



Hello Nikita,

On 23.05.16 21:27, Nikita Nefedov wrote:

When you pass an `int` to a `string` type parameter in weak mode
it's being coerced to the needed type (not just directly passed).

This is quite complex, because you'd need to copy zend_function
and all its members (without changing the original zend_function).

I would love to support it but all in all it comes down to
implementation here for me, so I'd rather do it in a separate
RFC.



I like the RFC, however I do not like this behavior.
This would behave differently then how current weak/strict mode works.

I was never a fan of the weak mode to begin with, but now introducing
something which deals in the area of argument passing and not behaving
to what a 2/3 majority agreed is IMHO a no-go. The current RFC does not
even mention that.

Maybe it's not feasible anyway, but in any case I'm missing
input/discussion in this area.

- Markus



Morning Markus,

Well, those strict/weak modes were initially invented for basic types,
not for composite types so I'd question if their support is needed at  
all...


For example regardlessly of what mode your file in, if you implement
an interface with `function foo(int $b)` you'd always have to implement
it with `int`, and not `float`.

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



Re: [PHP-DEV] [RFC] [Vote] Callable types (now: Callable prototypes)

2016-05-23 Thread Nikita Nefedov

On Mon, 23 May 2016 22:52:18 +0300, Levi Morrison <le...@php.net> wrote:

On Mon, May 23, 2016 at 1:19 PM, Nikita Nefedov <inefe...@gmail.com>  
wrote:



On 23 May 2016, at 19:31, Levi Morrison <le...@php.net> wrote:

A quick question before I vote: do callable prototypes allow for
default parameters in the signature? There are examples for having a
function passed that has a default parameters but I am not seeing it
anywhere in the callable prototype definition so I thought I'd ask.


Hey Levi,

Although it could be done as a later RFC, my stance on it is that  
default values don't belong to the prototype of the function.


Why I think that callable typehint doesn't need default values for  
params is: you either need this parameter to exist and even if there  
are cases where you'd like to pass some kind of 'default' value  
implicitly, you as a caller shouldn't impose on the callee  
responsibility to have this same value in his definition and instead  
just pass your argument explicitly... or if you don't need this  
parameter (as in you don't plan to pass anything explicitly) then you  
should just ask for a function without this parameter as there is  
clearly no need for it at all.


Moreover I would argue interfaces have it wrong here too: the fact that  
default values are part of an interface yet their invariance is not  
enforced, yields an interesting sort of possible LSP violation. F.e. if  
we have an interface Logger (a completely unreal example but it shows  
what can go wrong) with function 'log($message, $level = LOG_DEBUG);'  
and a funny implementation that decided to change default value of  
$level to LOG_ALERT, then all callers of Logger#log who relied on the  
fact that level if not specified, will be LOG_DEBUG, who also happen to  
get the funny implementation of Logger will produce unneeded noise in  
the logs with their alert level messages which were intended to be  
debug messages :(


Please document this restriction in the RFC. I guess I'm the only one
who expected it to be there since it didn't come up before, but it
just seems missing. You don't need to take it out of voting for this
clarification, imo.


Morning,

sure thing, added it in the RFC

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



Re: [PHP-DEV] [RFC] [Vote] Callable types (now: Callable prototypes)

2016-05-23 Thread Nikita Nefedov

Hi Bob,

When you pass an `int` to a `string` type parameter in weak mode
it's being coerced to the needed type (not just directly passed).

This is quite complex, because you'd need to copy zend_function
and all its members (without changing the original zend_function).

I would love to support it but all in all it comes down to
implementation here for me, so I'd rather do it in a separate
RFC.

If you meant accepting `function(string $foo){}` as an argument
of `callable(int)` parameter without coercing then this would
be impossible due the fact that this all is context-dependent.
Which means that the function which got `function(string $foo){}`
in place of `callable(int)` could itself be strict-mode
and when it would call this function it would raise a TypeError.


On Mon, 23 May 2016 20:05:50 +0300, Bob Weinand <bobw...@hotmail.com>  
wrote:



Hey,

I have a question regarding strict/weak types.

Currently, you cannot pass a callable function(string $foo) {} to a  
signature requiring (callable(int)), if I understood the code correctly.


But weak types actually should allow that as it's totally fine to pass  
an integer to a string in weak mode.


Is there any particular reason to this seemingly arbitrary restriction?

Bob


Am 23.05.2016 um 16:27 schrieb Nikita Nefedov <inefe...@gmail.com>:

Evening internals,

With this message I'd like to go to vote
with the Callable prototypes RFC targeted at 7.1:
https://wiki.php.net/rfc/callable-types

We've renamed it (previously was "Callable types") as RFC names often
dictate how users will call the feature and I want it to be more
accurate/descriptive.

Also the reflection part was added although I'm short on time currently,
so implementation for that will be ready later. (speaking of  
implementation,

it also currently doesn't use cache_slots - also something I'll add when
I have a little bit of time)


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



Re: [PHP-DEV] [RFC] [Vote] Callable types (now: Callable prototypes)

2016-05-23 Thread Nikita Nefedov

> On 23 May 2016, at 19:31, Levi Morrison <le...@php.net> wrote:
> 
>> On Mon, May 23, 2016 at 8:27 AM, Nikita Nefedov <inefe...@gmail.com> wrote:
>> Evening internals,
>> 
>> With this message I'd like to go to vote
>> with the Callable prototypes RFC targeted at 7.1:
>> https://wiki.php.net/rfc/callable-types
>> 
>> We've renamed it (previously was "Callable types") as RFC names often
>> dictate how users will call the feature and I want it to be more
>> accurate/descriptive.
>> 
>> Also the reflection part was added although I'm short on time currently,
>> so implementation for that will be ready later. (speaking of implementation,
>> it also currently doesn't use cache_slots - also something I'll add when
>> I have a little bit of time)
>> 
>> --
>> PHP Internals - PHP Runtime Development Mailing List
>> To unsubscribe, visit: http://www.php.net/unsub.php
> 
> A quick question before I vote: do callable prototypes allow for
> default parameters in the signature? There are examples for having a
> function passed that has a default parameters but I am not seeing it
> anywhere in the callable prototype definition so I thought I'd ask.

Hey Levi,

Although it could be done as a later RFC, my stance on it is that default 
values don't belong to the prototype of the function.

Why I think that callable typehint doesn't need default values for params is: 
you either need this parameter to exist and even if there are cases where you'd 
like to pass some kind of 'default' value implicitly, you as a caller shouldn't 
impose on the callee responsibility to have this same value in his definition 
and instead just pass your argument explicitly... or if you don't need this 
parameter (as in you don't plan to pass anything explicitly) then you should 
just ask for a function without this parameter as there is clearly no need for 
it at all.

Moreover I would argue interfaces have it wrong here too: the fact that default 
values are part of an interface yet their invariance is not enforced, yields an 
interesting sort of possible LSP violation. F.e. if we have an interface Logger 
(a completely unreal example but it shows what can go wrong) with function 
'log($message, $level = LOG_DEBUG);' and a funny implementation that decided to 
change default value of $level to LOG_ALERT, then all callers of Logger#log who 
relied on the fact that level if not specified, will be LOG_DEBUG, who also 
happen to get the funny implementation of Logger will produce unneeded noise in 
the logs with their alert level messages which were intended to be debug 
messages :(
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



[PHP-DEV] [RFC] [Vote] Callable types (now: Callable prototypes)

2016-05-23 Thread Nikita Nefedov

Evening internals,

With this message I'd like to go to vote
with the Callable prototypes RFC targeted at 7.1:
https://wiki.php.net/rfc/callable-types

We've renamed it (previously was "Callable types") as RFC names often
dictate how users will call the feature and I want it to be more
accurate/descriptive.

Also the reflection part was added although I'm short on time currently,
so implementation for that will be ready later. (speaking of  
implementation,

it also currently doesn't use cache_slots - also something I'll add when
I have a little bit of time)

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



Re: [PHP-DEV] [RFC][VOTE] Closure from callable

2016-05-16 Thread Nikita Nefedov

On Mon, 16 May 2016 03:56:38 +0300, Sara Golemon <poll...@php.net> wrote:

On Sun, May 15, 2016 at 11:20 AM, Nikita Nefedov <inefe...@gmail.com>  
wrote:

why would you need to support a $this->fieldName case though?


Because to not support it would be to deliberately design in a new
flavor of inconsistency into the language. $obj->memb is a property
access in PHP.  Making it suddenly mean "method" is a significant
change (and one which belongs in a major version if at all).

-Sara


The whole idea is not in the syntax here, but in the notion
that this access can only be static (so there'd be no way to
do `$cb = [$this, "methodName"]; callable($cb)` - you'd have
to call `Closure::fromCallable($cb)` instead).

If you don't like the fact that `$obj->methodName` looks like
a field access then there are ways around this.
Because we still need a static way of exporting function
references (whether it'd be as a closure or array). Other
proposals were using `$obj->method::FUNCTION` syntax or something
similar for example...

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



Re: [PHP-DEV] [RFC][VOTE] Closure from callable

2016-05-15 Thread Nikita Nefedov

> On 15 May 2016, at 20:29, Dan Ackroyd  wrote:
> 
> Hello,
> 
> I've opened the voting for the Closure from callable RFC -
> https://wiki.php.net/rfc/closurefromcallable
> 
> Just to note, some people I've spoken to have expressed a desire to
> have a more powerful syntax where 'bare' function names are used,
> like:
> 
> callable(someFunctionName)
> callable($this->method)
> 
> I fully agree with those people, however I can't see anyway to do that
> before PHP 8. It would almost certainly need some clean up of the
> allowed syntax to disambiguate what `$this->method` means for:
> 
> class Foo {
>   public $method;
>   public function method() { }
> }
> 
> Leaving that top-level function name available for future versions,
> where we might be able to support it properly, is one of the reasons
> to use the more verbose function name.

Hey Dan,

why would you need to support a $this->fieldName case though? If it's a field 
it probably already contains a closure (or, well, if you need to make a closure 
from arbitrary callable we could have a Closure::fromCallable named ctr). 
Instead of making a function 'callable()', we could make a language construct:

   expr:
   ...
   | T_CALLABLE '(' callable_expr ')'

   callable_expr:
   '$this->' function_name
   | class_name '::' function_name
   | function_name

This would have an advantage of being statically checked (hence easier 
refactoring in IDEs).

I see merging symbol tables as a pretty big of a deal for too much people, this 
thing alone could easily create another case of Python 3 syndrome.



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



Re: [PHP-DEV][RFC] Callable Types

2016-04-26 Thread Nikita Nefedov

Bringing this thread to the main one

On Sun, 24 Apr 2016 06:27:39 +0300, Mathieu Rochette   
wrote:



I've seen someone mentioning variadics so I made a few small tests, I
think those two should work (they currently don't):

https://3v4l.org/eZgR9/rfc#rfc-callable_typehint
https://3v4l.org/N7i0u/rfc#rfc-callable_typehint

and this one should not:

https://3v4l.org/fcRlT/rfc#rfc-callable_typehint


Hey,

You're right, this code should be valid

function foo(callable() $a) { $a(); }
foo(function (...$args) {});

But it gets into the same problems like optional params when it is typed

function foo(callable() $a) { $a(123); }
foo(function (A ...$args) {});

Now to the question why would `foo()` call `$a` with additional arguments
even though it assumes `$a` is of type `callable()`? Well at first
because it can - this is enough for it to be not type safe :P
Long answer is: in the real life there will definitely be cases where
this would allow users to shoot their feet, take this example:

function map(/* array | Traversable */ $collection, callable($value,  
$index) $mapper) {

$out = [];
foreach ($collection as $index => $value) {
$out[] = $mapper($value, $index);
}
return $out;
}
...
function renderPost(Post $p, bool $asAdmin = false) {
return render("post_template", ["post" => $p, "asAdmin" =>  
$asAdmin]);

}
...
$renderedPosts = map($posts, "renderPost");
// here developer would get fatal at the line `$out[] =  
$mapper($value, $index);`

// if optional parameters were supported
// Without them though, he gets TypeError when he passes "renderPost"  
to map()

// And it says nicely what exactly he has done wrong

Even now though, he could get into this situation if `$asAdmin`
parameter was not properly typed, but that would be on him as
he'd need to voluntarily drop those types for which I don't see
a reason to do so.

Now talking about an immediate solution to hypothetical problem we are  
facing
there is an easy solution - if you have a functional library, you'll  
probably

have there `partial_any` function of some kind (ex. [0]),
so what you could instead do is:

$renderedPosts = map($posts, f\partial_any("renderPost",  
f\placeholder(), true));


This would always pass `true` to a second parameter, but leave the first  
one.


[0]  
https://github.com/lstrojny/functional-php/blob/master/docs/02-partial-application.md#partial_any


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



Re: [PHP-DEV][RFC] Callable Types

2016-04-26 Thread Nikita Nefedov
On Sat, 23 Apr 2016 20:44:27 +0300, Jesse Schalken   
wrote:


I see. So it's the combination of not erroring when more parameters are  
passed than a function accepts, and >permitting methods to add extra  
optional parameters that is wrong. So without the former being  
fix/deprecated, >the correct thing to do is to disallow extra optional  
params. Makes sense.


Are there any valid use cases for passing extra parameters to a function  
any more, now that there is the varargs >syntax to replace  
func_get_args()? If not, maybe it could be deprecated by this RFC.


Regarding references, by-ref invariance for parameters makes sense, and  
is what method compatibility does. >According to method compatibility  
and call-time behaviour however, return by-ref is effectively a subtype  
of >return by-value:



function _ref() {
   $f = 0;
   return $f;
}


function returns_val() {

   return 1;
}


$v1 = returns_ref(); // ok

$v2 =& returns_ref(); // ok
$v3 = returns_val(); // ok
$v4 =& returns_val(); // Notice: Only variables should be assigned by  
reference


interface Methods {
   function ();
   function returnsVal();
}


class ReturnRef implements Methods {

   function () {} // ok
   function () {} // ok
}


class ReturnVal implements Methods {
   function returnsRef() {} // Fatal error: Declaration of  
ReturnVal::returnsRef() must be compatible with >>&  
Methods::returnsRef()

   function returnsVal() {} // ok
}


Otherwise it LGTM

cheers


Hey,

sorry for slow reply, been busy working...

I don't really see use cases for func_get_args any more, variadics do
it better (more obvious/documentative for the caller). But this is
a huge BC break, I'm afraid it could be deprecated only in 8.0
and still that would be pretty big of an event... Definitely a matter
of another RFC.

You're right about return references, I've made changes in the RFC
about it. There's a problem with syntax though. So now passing a
function that returns a reference to a parameter that expects value
returning function is working. But you can't declare in the callable
typehint that you only need functions that return reference.
That is, apart from syntax limitations, I'm always happy to
discourage usage of references :P

Touching optional parameters again - there was also my oversight,
actually passing function with optional parameters is fine
*as long as they are not typed*. Otherwise it can lead to
weird type errors. So that was changed as well.

Thanks to 3v4l guys, all these changes are on https://3v4l.org/
already, you can check them out :)

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



Re: [PHP-DEV][RFC] Callable Types

2016-04-23 Thread Nikita Nefedov
On Sat, 23 Apr 2016 14:18:56 +0300, Dan Ackroyd   
wrote:



On 22 April 2016 at 05:12, Marcio Almada  wrote:

Hello everyone,

We just completed the draft for the "Callable Types" RFC.


There seems to be one thing missing from the RFC; please could you add
an example where the parameter and return types are also 'typed'
callables?

Presumably it would look something like this?

function reduce(int $a, int $b, callable(int, callable(int, int):int
$math):int $reducer): callable(int, int):int {
  return $reducer($a, $b);
}

Are there any limits to how far down the callable type can be defined ?

cheers
Dan


Hey Dan,

thanks for reviewing.

I have just added a paragraph about nested callables, I'll copy paste it  
here:


Nested callables can be used with no imposed limit on the nesting level.

function foo(callable(callable(int)) $cb) {
$cb(function (int $i) {
var_dump($i);
});
}

foo(function (callable(int) $intPrinter) {
$intPrinter(123);
});

There's currently no way to reference callable signature from within  
itself, meaning there's no way to make recursive signatures like below:


function bar(callable(int $number): callable(int $number):  
callable(int $number): parent_callable $recursiveCb) { // this wouldn't  
work currently

}

To add to that, nested callables can get pretty unreadable quickly, both  
of these problems would be best solved by a typedef feature of some kind,  
added to PHP later.


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



Re: [PHP-DEV][RFC] Callable Types

2016-04-23 Thread Nikita Nefedov
On Sat, 23 Apr 2016 10:46:38 +0300, Jesse Schalken   
wrote:


This is great. The gaps in PHP's type annotations are slowly being  
filled.

:)

Are the rules for compatibility between callables the same rules for
compatibility between methods in classes/interfaces? Because presently,
this is allowed:

interface Test {
public function testMethod();
}

function foo1(Test $x) { }

foo1(new class implements Test {
public function testMethod(int $extraParam = 0) { }
});


but, according to the RFC, this would not be:

function foo2(callable():void $x) { }

foo2(function (int $extraParam = 0) { });


I don't see why they should be different.

I also didn't see anything mentioning reference parameters/returns. I
assume it just follows the rules for method compatibility?


Hey Jesse,

Thanks for reading the RFC.

First and foremost - no, the rules for compatibility between callables
and method implementations are different at least because our
inheritance model currently doesn't support variance for every case:

if you have

class B extends A {}

interface Foo {
function foo(B $b);
}

then implementation of `foo()` can never have `foo(A $a)` signature,
which is crucial for callables for some cases. Note that callables
have runtime variance, where classes would have compile-time variance).

So, in this way, callables have it right (it is desirable for classes
to have variance as well, but currently it's not possible as there is
a need for another compilation phase for verifying variance).

What about your case of variance with extra optional parameter, it is
actually not type safe with the current way of how PHP works (it's
covered in the end of "Variance and Signature Validation" part).
The problem lies in the notion that passing extra arguments to the
function (the ones it doesn't even expect nor use) is considered
valid and doesn't throw an error.
So if you have a function that accepts optional argument of type B and
you pass this function as a parameter of type `callable() $cb`, then
it would be perfectly valid to call it as `$cb(new A);` because you
assume that $cb is of type `callable()` and that means if you pass
anything extra - it shouldn't Fatal. But in this case it would.

While I agree that your use case is legit and ideally should be
supported, I don't think it is safe to support it until PHP deprecates
passing extra args to functions that don't expect them (which is very
troublesome to implement due to BC).

Anyway, changing this behavior of callable type later on wouldn't
break BC so the gates will still be open.

I've just added a part about references to the RFC (and found a
bug in the implementation, thanks for that =)), I'll just copy
and paste it here:

Reference parameters are supported: no variance is applied to
the fact whether parameter is referential or not.

Example:

function foo(callable(&$byref) $cb) { }

foo(function (&$bar) { }); // valid
foo(function ($bar) { }); // TypeError: Argument 1 passed to foo()  
must be callable of compliant signature: callable(&$byref), callable($bar)  
given


function bar(callable($byval) $cb) { }

bar(function (&$bar) { }); // TypeError: Argument 1 passed to bar()  
must be callable of compliant signature: callable($byval), callable(&$bar)  
given


Functions returning a reference are not different from functions returning  
a value in PHP, for the caller, hence both are interchangeable:


function foo(callable(): A $cb) { }

foo(function (): A { return new A; });
foo(function &(): A { static $a; $a = $a ?: new A; return $a; }); //  
both would pass the boundaries of a type check


(the last one has error in the current implementation, I'll fix it later)

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



Re: [PHP-DEV][RFC] Callable Types

2016-04-22 Thread Nikita Nefedov
On Fri, 22 Apr 2016 07:12:13 +0300, Marcio Almada <marcio.w...@gmail.com>  
wrote:



Hello everyone,

We just completed the draft for the "Callable Types" RFC. This RFC has  
been
recently mentioned during other type related threads on this mailing  
list,

so it feels to be the right time to put the proposal in context:

The proposal is at https://wiki.php.net/rfc/callable-types

The W.I.P patch is available for testing through http://3v4l.org under  
the

RFC tab.

We count with your detailed feedback and insights. Let's have a nice,
respectful and
constructive conversation about the RFC and work on possible  
improvements!


Thanks
Nikita Nefedov
Márcio Almada


Hello internals,

We're still having a hard time finding a proper format for error message
about incompatible callable being passed.

Right now it looks like this:

Uncaught TypeError: Argument 3 passed to reduce() must be callable of  
compliant signature: callable(integer, integer): integer, callable($a, $b,  
$c) given, called in ...


Although it goes in the fashion with all other TypeErrors but it's
obviously very cryptic and it will be hard to read for human.

One of the alternatives Marcio proposed was:

Uncaught TypeError: Argument 3 passed to reduce() must be compliant  
with callable(integer, integer): integer, incompatible callable($a, $b,  
$c) received, called in ...


This is remarkably more readable but if you have any suggestions you're  
welcome.
Actually I think other type errors are not very readable as well, take  
f.e.:


Argument 1 passed to foo() must be an instance of string, boolean given

The fact that `string` and `boolean` are separated by only one comma,
and the way `boolean given` is worded (verb after noun) makes it harder
to read. So maybe we could reconsider type error messages and change them
to something more user-friendly, if there's support for this idea...

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



Re: [PHP-DEV] Object getter method optimization

2016-03-20 Thread Nikita Nefedov

On Sat, 19 Mar 2016 23:40:09 +0300, Andrea Faulds  wrote:


Hi Lin,

Lin Yo-An wrote:

Since the original approach doesn't work, here comes another new idea:

When executing method call on an object, if we found the method body are
just 2 op codes (FETCH_OBJ_R and RETURN), we then denote the method is a
"getter method"

And the next time, when we execute the same method, we found the "getter
method" flag, we simply execute FETCH_OBJ_R on that object and return  
the

value to avoid extra op code execution time.

Do you think if this could work?


For a while I'd also been wondering if we could implement some  
implementation along these lines. Another approach could be possibly  
replacing such methods with an C implementation (though I don't know if  
non-internal classes can have internal methods).


I don't know how successful it will be, but I'm interested to hear how  
much improvement it gives if you get it working.


Thanks!



I was playing with this idea sometime ago, it gives good performance boost  
for code like `for ($i = 0; $i < 10; $i++) $a->getFoo();` but in the  
end of the day it's a very limited optimization.
If you abstract away from getters and say you want to optimize more and  
more small functions like this one, you end up realizing that what you're  
actually doing is what JIT compilation would do in a more generic way.


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



Re: [PHP-DEV] Re: [RFC] Callable constructors

2016-02-26 Thread Nikita Nefedov

On Fri, 26 Feb 2016 14:28:19 +0300, Andrea Faulds  wrote:


Hi Rowan,

Rowan Collins wrote:

On 25/02/2016 17:40, Andrea Faulds wrote:

Snipped for brevity, but I agree with your sentiment here. Making
__construct more magic seems like an imperfect solution to this. I'm not
sure making a new magic method (new, __new, etc) is much better though,
since it would serve such a limited purpose.


Yeah, I do wonder if ::new would really be worth it.



Then we could add to that a special case for constructors:

- Callable::forConstructor(string $class_name)



Oh, that's quite a clean solution, I like that. Heck, no need for  
Callable, we already have ->getClosure() in Reflection. A modified  
version of that for constructors could work  
(ReflectionClass::getConstructorClosure() ?).


Thanks.


Hey Andrea,

This would still not solve Dan's problem though. Which is representing  
`new Class` as a serializeable callable.


I really think ::new() makes the most sense here (and looks quite alright  
unlike `Class::__construct()`).


Although making a special case for `new ...` is pretty simple, I too have  
felt the need for callable constructors plenty of times, that would be  
useful.


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



Re: [PHP-DEV] In a destructor, how to detect if an exception is currently in flight?

2015-10-28 Thread Nikita Nefedov

Hi Erik,

On Wed, 28 Oct 2015 16:28:59 +0300, Erik van Velzen  wrote:


Thanks for your input.

I did not try-catch because it doesn't really work, you either
duplicate rollback code or get excessive nesting. Real code will
obviously be more complicated than the examples.
Also in both cases the handlers are many lines apart from the actual
transaction call.

Duplicate rollback code:

try {
transactionOne();
}
catch (\Throwable $e) {
   rollbackTransactionOne();
   throw $e;
}

try {
transactionTwo();
}
catch (\Throwable $e) {
rollbackTransactionOne();
rollbackTransactionTwo();
throw $e;
}
finally {
cleanupTransactionTwo();
}

try {
   transactionThree();
}
catch (\Throwable $e) {
rollbackTransactionOne();
rollbackTransactionTwo();
rollbackTransactionThree();
throw $e;
}

logTransactionOne();
logTransactionTwo();
logTransactionThree();


In C goto is usually used for this kind of problem, this is how it's  
usually done:


https://gist.github.com/nikita2206/dc48c9f14db61420751e

here's a first article I could find about it  
http://eli.thegreenplace.net/2009/04/27/using-goto-for-error-handling-in-c


What you could also use though is a generator function:

https://gist.github.com/nikita2206/64959e63ebb49d6ce0c8

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



Re: [PHP-DEV] Re: [PHP Wiki] Your DokuWiki password

2015-10-02 Thread Nikita Nefedov
On Fri, 02 Oct 2015 12:58:30 +0300, Andréas H.   
wrote:



My login is : screamz

I would like to edit my profile, first at all.

Then Sometimes I would like to edit french translation that are not true,
(if I can ?)

Thanks

Best regards

2015-10-02 11:54 GMT+02:00 :


Hi Andréas Hanss!

Here is your userdata for PHP Wiki at https://wiki.php.net/

Login: screamz
Password : tamwimzuv52.




Happy Friday I guess :D

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



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

2015-10-01 Thread Nikita Nefedov
On Thu, 01 Oct 2015 13:48:52 +0300, Rowan Collins  
 wrote:



Levi Morrison wrote on 01/10/2015 04:06:

I'm going to ask everyone to stop saying that auto-closing is bad
unless they also provide a demonstration of why it was bad.


Please see my e-mail from last night, or Rasmus's in the original  
thread. It is "bad" (or, controversial) because it is a fundamental  
change to PHP's scoping rules, which currently treat all variables  
denoted by "$foo" as local to the current function, without exception.


And yet we have super-globals. You can also access variables of one  
script's global scope from another script's global scope without importing  
or anything like that. I wouldn't say that PHP has or follows any  
idiomatic "way" of how scopes should work, it's just evolutionary.




I'm also going to ask everyone to stop suggesting new syntax for
importing variables. If use() is a pain then auto-importing the used
variables is a good solution. If it's not a pain why are you
suggesting new syntax?


Because the feature is being described as "short closures", or as a new  
syntax, so people are looking for ways to make closures shorter without  
changing the functionality.


If auto-capture is the main feature you are interested in, and syntax  
just a by-product, then it might be sensible to make that clear. As a  
straw man, it would be possible to have auto-capture closures with no  
new syntax at all, e.g. function($x) use(*) { return $x * $y; }


I believe Levi's and Bob's intentions are not to introduce auto-capture  
but to add short closures, auto-capture being a tool that works best to  
help in achieving this. `use(*)` just as long as `use($y)`, and the  
shorter version where you need to separate args from uses with semicolon  
will be harder to read (ex.: `fn($x; $y) => $x * $y` vs `fn($x) => $x *  
$y` - it's not obvious at all what semicolon does. Whereas with auto  
capture you can at least guess that this variable will be captured from  
defining scope, if you don't know how this feature works).


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



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

2015-10-01 Thread Nikita Nefedov
On Thu, 01 Oct 2015 15:33:51 +0300, Rowan Collins  
 wrote:


That's not how Rasmus expressed it  
[http://marc.info/?l=php-internals=144107616411299=2]:


 > I made a very deliberate decision In the very first implementation of  
PHP to avoid scope side-effects like this. Inside a function everything  
is local unless explicitly declared not to be. This has carried through  
for the past 20+ years in slightly different ways, but the basic rule  
has stayed consistent even for closures.


Ok, it proves that it's not evolutionary that scopes aren't chained.  
Taking my words back.



It is a tool for making them shorter, yes, but it is not the only way,  
and it comes with a cost of changing established behaviour. Again, look  
at C++'s lambda syntax - it is much shorter than PHP's, but requires a  
list of all variables from the outer scope being captured.


C++11 doesn't *require* the list of all variables, but it does require  
explicit "wildcard" ([=] for copy semantics, [&] for capturing by  
reference).
But C++ is not the best place for picking up syntax choices, quite frankly  
it's one of the least readable languages in a way that it allows you to  
write very cryptic code easily (but still allows to write perfectly  
readable code as well).
I'm not aware of reasons why ISOCPP decided that automatic capture should  
be disabled by default, maybe it was because it was hard to decide whether  
it should default to by-value or to by-reference semantics, or maybe []  
tokens were needed because of parsing limitations.



You've picked on one syntax I explicitly labelled as "a straw man", and  
one idea which was proposed by somebody else a few hours ago, and use  
those to somehow dismiss the whole idea of a short syntax which lists  
captured variables. I have come up with about a dozen different ideas in  
various parts of this discussion, and could list dozens more. They would  
all have their pros and cons, but I don't see how you can dismiss the  
whole concept, UNLESS you consider the auto-capture to be an end in its  
own right, rather than "just a way of making it shorter".


I don't think there was a dozen of different ideas, I could only find  
those about `lambda(arg-list; use-list; expression)` and variations of it  
with different keywords and different return-type syntax.
I do understand that this is quite subjective, but neither this syntax nor  
`fn(arg-list; use-list) expression` look obvious and easily readable to me.


And one thing that makes auto capture much better choice than explicit  
capture (as it've been said a couple of times already) is partial  
application:


$mul = fn($x) => fn($y) => fn($z) => $x * $y * $z;

Looks simpler than:

$mul = fn($x) => fn($y; $x) => fn($z; $x, $y) => $x * $y * $z;

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



Re: AW: [PHP-DEV] [RFC] [Discussion] Short Closures

2015-09-07 Thread Nikita Nefedov

On Mon, 07 Sep 2015 11:46:18 +0300, Robert Stoll  wrote:


Hi Bob


-Ursprüngliche Nachricht-
Von: Bob Weinand [mailto:bobw...@hotmail.com]
Gesendet: Montag, 31. August 2015 21:29
An: PHP Internals
Betreff: [PHP-DEV] [RFC] [Discussion] Short Closures

I had this RFC in draft since some time, but delayed it due to all the  
ongoing PHP 7 discussions. Also we have no

master

branch to merge features in until 5.4 EOL. Thus I'm reviving this now.

Time for the first RFC targeting PHP 7.1 (assuming PHP 8 isn't going to  
be the next version ;-)):


The short Closures RFC:
https://wiki.php.net/rfc/short_closures

Hoping for constructive feedback,
Bob
--
PHP Internals - PHP Runtime Development Mailing List To unsubscribe,  
visit: http://www.php.net/unsub.php


I would like to see a short syntax for closures in PHP but would suggest  
to use different symbols for the operator. Why

not use --> ?



--> is a shift-reduce conflict. It's undecidable if this expression should  
return boolean or a closure:

`$foo-->$bar` (is it `$foo --> $bar` or `$foo-- > $bar`)

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



[PHP-DEV] Requesting RFC karma

2015-09-03 Thread Nikita Nefedov

Hey everyone,

I'm asking for some RFC karma for wiki account nikita2206
in preparation of callable typehints RFC [0]
with Marcio, and some other RFCs in the future.

Thanks in advance \O/

[0] https://wiki.php.net/rfc/callable-types

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



Re: [PHP-DEV] [RFC] [Discussion] Short Closures

2015-08-31 Thread Nikita Nefedov
On Tue, 01 Sep 2015 00:05:35 +0300, Stanislav Malyshev  
 wrote:



Hi!


I had this RFC in draft since some time, but delayed it due to all
the ongoing PHP 7 discussions. Also we have no master branch to merge
features in until 5.4 EOL. Thus I'm reviving this now.

Time for the first RFC targeting PHP 7.1 (assuming PHP 8 isn't going
to be the next version ;-)):

The short Closures RFC: https://wiki.php.net/rfc/short_closures


I personally don't see much advantage in making PHP code less readable
and harder to parse. Also, "automatically use () all of the (compiled)
variables" does not look like a good idea - first, users have no idea
what compiled variables are, so the result would be unpredictable for
them, second, if there are a lot of variables in the scope (like global
scope) it would have huge performance costs for no gain.
Also, this syntax does not allow "use by-ref" which the existing syntax
does allow.

I think we already have syntax for anonymous functions and it works. The
only addition in this RFC is automatically gobbling up all local
variables, which in vast majority of use cases is not what the function
needs.


Hi Stas,

Capture of all variables from the current scope is not the only addition  
in this RFC. The main addition (which is extended by that btw) is making  
the syntax shorter. Which, in turn, makes it easier to write and read  
closures. I've had a huge lot of cases where I would benefit from it,  
things like this:


  $collection = array_filter(array_map(function (Type $el) { return  
$el->getStuff(); }, $collection));


It would be much easier to read and write with the short syntax:

  $collection = array_filter(array_map((Type $el) ~> $el->getStuff(),  
$collection));


Just because, I'll say it, the less symbols you have to read the faster  
you'll read it. To some extent, of course, a counter-example being Perl  
language. But I don't think that we are even close to it.


Your point about capturing too much if you have too much in the global  
scope is legit but in this case I'd say two things: you can still use long  
closure syntax, and second you have a problem with global scope not short  
closures.


You see the main use case for anon. functions is when you need a  
*lightweight* callback for something. If it were a fat function I'd  
probably make it named and write tests for it. But when it's a small  
function, often consisting from only one expression it kinda bothers me  
when the body of this function takes less keystrokes than 'function' and  
'return' keywords...


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



Re: [PHP-DEV] [RFC] [Discuss] Random Functions Throwing Exceptions in PHP 7.0.0

2015-08-23 Thread Nikita Nefedov


 On 23 Aug 2015, at 18:37, Thomas Bley ma...@thomasbley.de wrote:
 
 
 consider this code:
 
 declare(strict_types=0);
 ini_set('display_errors', '1');
 
 function get_random_int(): int {
 return false;
 }
 echo get_random_int();
 
 and then use strict_types=1

So you're implying that in case of returning false with strict_types turned on 
that would just throw a TypeError? That would be a bug in PHP. If you were 
saying that in this case it should throw a different kind of error (the one 
that was proposed by Anthony initially) then it wouldn't make sense again 
because then you're creating a straight relation between having strict_types 
mode turned on and random_int() throwing exception about not getting a reliable 
source of entropy.


 Even correct return values of random_int() might create bad passwords.
 So I propose to have a function in core which tests the strength of the 
 password:
 
 $password = '';
 for ($i = 0; $i  10; $i++) {
 $password .= $characters[random_int(0, 30)];
 }
 if (password_strength($password)  PHP_PASSWORD_STRONG) {
   throw new Exception(password not strong enough);
 }

I don't think it's a good idea, a language delivers features that user would 
have a hard time implementing themselves, a small blocks from which you can 
build whatever you want. A function that checks if a string contains 
alpha-numeric symbols as well as punctuation is pretty easy to implement in 
user land.

PS sorry Thomas, I sent it to you personally, not to ML
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] ::class wrong case

2015-05-25 Thread Nikita Nefedov

On Mon, 25 May 2015 20:47:32 +0300, Marc Bennewitz dev@mabe.berlin wrote:


Hi,

I have noted that detecting a class name using ::class it will return  
the called case instead of the original case.

see http://3v4l.org/97K36

That's annoying as I like to check the right class case on autoload to  
detect mistakes.


Sure, class names in PHP are case-insensitive but filesystems aren't and  
most autoloader using the FS to find the right file. To catch such kind  
of mistakes I would like to implement a fast check in my autoloader to  
get noted on development instead on production. It's currently only  
possible with ReflectionClass but this will be much slower as with  
::class.


Are there any reasons to get the called case of the class instead or the  
original one?


Marc



This happens because ::class construction is evaluated at compiled time,  
without triggering autoloader. That means compiler doesn't know what will  
be the actual name of a class, it just gives you what you asked for.


It's currently only possible with ReflectionClass but this will be much  
slower as with ::class.


It's only possible with ReflectionClass if this class was already loaded.  
There's one way for your autoloader to know if the class name has  
characters in a wrong case - build a class map and do a check based on  
this map.


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



Re: [PHP-DEV] [RFC][Accepted] Scalar Type Declarations V0.5

2015-03-18 Thread Nikita Nefedov
On 18 Mar 2015 15:52, Pavel Kouřil pajou...@gmail.com wrote:

 Hello,

 I made that conclusion because in the first example, the library kinda
 forces strict mode rules on the caller, even if he doesn't want to use
 strict mode - this makes the interoperability of the two modes
 problematic.

This is incorrect, library force itself to use right types, not you. I
don't see any problems here. The only thing that for sure lacks in PHP and
that would make STH better is callable signature types.

 Also, the other possible outcome of the scenario (respecting the mode
 of the place where the callback is declared), is IMHO problematic as
 well, because it does not respect the strict mode of the place where
 it is called, making it inconsistent with how the dual mode RFC works
 in general.

It doesn't matter where the callback or function was declared, it only
matters where it was called. It pretty much is consistent.


Re: [PHP-DEV] [RFC][Accepted] Scalar Type Declarations V0.5

2015-03-18 Thread Nikita Nefedov
On 18 Mar 2015 14:32, Pavel Kouřil pajou...@gmail.com wrote:

 On Wednesday, March 18, 2015, Patrick ALLAERT patrickalla...@php.net
 wrote:
  Le mer. 18 mars 2015 à 10:56, Pavel Kouřil pajou...@gmail.com a écrit
:
 
  Hello,
 
  how will these examples work btw?
 
  // a.php
  ?php
  declare(strict_types=1);
  function foo($fn) {
  $fn(1);
  };
 
  // b.php
  ?php
  require 'a.php';
  foo(function (int $a) { return $a * 2; });
 
 
 
  // c.php
  ?php
  function foo($fn) {
  $fn(1);
  };
 
  // d.php
  ?php
  declare(strict_types=1);
  require 'c.php';
  foo(function (int $a) { return $a * 2; });
 
  I can't find this in the RFC. I'd intuitively expect error in the
  first example and the second one to work OK.
 
  Your intuition is correct.
 
 
  But at the same time, if there will be an error in the first example,
  it is IMHO a huge flaw with this RFC. :/
 
  Flaw vs. design choice. This is one of the reason that this aspect,
 amongst others, has been very debated.

 But if it works this way, the strict mode isn't optional and users of a
 library NEED to care which mode the library uses?

If library chose to use strict mode then the odds are it will take care of
passing right types to callbacks and interfaced methods.

Saying that strict mode isn't optional is not true, I don't see why you
have made this conclusion.


Re: [PHP-DEV] About declare(strict_types = 1)

2015-03-16 Thread Nikita Nefedov
On Mon, 16 Mar 2015 14:33:00 +0300, Yasuo Ohgaki yohg...@ohgaki.net  
wrote:



Hi Derick,

On Mon, Mar 16, 2015 at 8:18 PM, Derick Rethans der...@php.net wrote:


To be frank, I don't think I don't like this is a terribly good reason
to vote against (or for something). What is important is how many people
would actually benefit from a feature, without it causing issues for
others. I am certainly no fan of the declare *syntax*, but I do know,
from talking at conferences that many many developers would like to see
scalar type hints in some way — both weak (mode 1 of the STHv5 RFC), and
strict (mode 2). It even caters for people that don't want to use them
at all, as they can simply not use them. I also know, that without a
dual mode, it seems very unlikely for scalar type hints to make it
into PHP 7, and I don't think that is what users want. As this is our
*best* bet, I can only vote yes.



Are you sure on your bet?

lib.php:
?php
declare(strict_types = 1);
function foo(int $a) {
// no function call here
}
?
The declare here does just nothing.

a.php:
?php
require lib.php;
foo(123); // will work
?

b.php:
?php
declare(strict_types = 1);
require lib.php;
foo(123); // will give an error
?

This behavior is unacceptable.
Caller (a.php, b.php) must satisfy lib.php expectation to make lib.php
work as it should. Otherwise, all kinds of unexpected for lib.php and  
it's

users may happen.


When called from a.php, foo() will get and int(123), this is exactly what  
is expected. Author of a.php acknowledges that all arguments in fcalls  
from this file will be converted to appropriate types, this is basically  
how all our internal functions work currently and it's perfectly  
acceptable. But if you don't want this kind of type juggling then you  
opt-in strict types. This is basically as easy as it gets, I don't see any  
way to make it simpler. There's nothing to evolve in this RFC, it covers  
pretty much everything and the idea of allowing for caller to make a  
decision is, in my opinion, a great win in this situation.


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



Re: [PHP-DEV] About declare(strict_types = 1)

2015-03-16 Thread Nikita Nefedov
On Mon, 16 Mar 2015 14:50:16 +0300, Yasuo Ohgaki yohg...@ohgaki.net  
wrote:




I already showed real world example how this could be fail.

If we need this kind of behavior. I would suggest to have type affinity
like SQLite for
$_GET/$_POST/$_COOKIE.

https://www.sqlite.org/datatype3.html

This would work better to work with strict types.



I don't see how, given your example, anything would fail. Do you imply
that function would get coerced value, but outside of the function
you would still have a string and the problem that this string could
contain anything?

If that's what you were trying to say then I don't consider this as a
problem, it's natural flow. If you were to implement type verification
in your function on your own you'd get the same results.

Perhaps you meant something different?

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



Re: [PHP-DEV] [RFC][VOTE] In Operator

2015-03-16 Thread Nikita Nefedov
On Mon, 16 Mar 2015 12:09:42 +0300, Lester Caine les...@lsces.co.uk  
wrote:



On 16/03/15 08:55, Marco Pivetta wrote:

PEAR surely isn't where you'd look for new code nowadays: it's a legacy
repository.


Give me an alternative?
I've had to update my own cope of PEAR so it's clean E_STRICT, but it is
still essential to maintain legacy code bases which are not going
anywhere soon.
We NEED a modern replacement, but nothing is available?



There are composer [1] and pickle [2].

Please refrain from your over-frequent comments in this mailing list  
before doing research on the subject, you tend to create an informational  
noise when you do this.


[1] https://getcomposer.org
[2] https://github.com/FriendsOfPHP/pickle

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



Re: [PHP-DEV] [RFC] Exceptions in the engine

2015-02-20 Thread Nikita Nefedov
On Fri, 20 Feb 2015 12:39:33 +0300, Tony Marston tonymars...@hotmail.com  
wrote:


I disagree. Exceptions were originally invented to solve the  
semipredicate problem which only exists with procedural functions, not  
object methods. Many OO purists would like exceptions to be thrown  
everywhere, but this would present a huge BC break. If it were possible  
get these functions to throw an exception ONLY when they are included in  
a try ... catch block then this would not break BC at all.




Tony, first of all - this still breaks BC, because exception is being  
thrown in a place where it used not to be...


When some function's result heavily depends on the context it makes said  
function much harder to reason about. And creates mental overhead for  
those who'll have to read the code with this function.


And again, if you need exceptions for fopen please consider using  
SplFileObject.


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



Re: [PHP-DEV] Digit separators for numeric literals

2015-02-19 Thread Nikita Nefedov
2015-02-19 6:44 GMT+04:00 Rasmus Lerdorf ras...@lerdorf.com:

 I think it will be difficult to find a separator character that doesn't
 make a mess of the grammar.

   my_func(1,999,999) obviously doesn't work
   my_func(1'999'999) as per C++14 clashes with our single-quoted strings
   my_func(1_999_999) like in ADA might work

 but _999_ would need to work as well and _ is a valid char in a constant
 so you can have a constant named _999_.

   - nope
   # nope
   @ nope
   ~ nope
   ! nope
   % nope
   ^ nope

 We went through this for the namespace char, and there simply isn't a
 typable single character left to use for something like this. _ is the
 closest but it would require some changes and BC breaks which I am not
 sure is worth for what appears to me to be a not-so critical feature.

 Now if we went into Unicode territory, we could do it. eg.

   my_func(1 999 999) U+1680 (although it looks too much like a -)
   my_func(1 999 999) U+205F (mathematical space)
   my_func(1٬999٬999) U+066C (Arabic thousands separator)
   my_func(1·999·999) U+00B7 (middle dot)

 The last one looks best to me, but we'd need a team of people working in
 shifts to answer the, How do I type this? question.

 -Rasmus



Hey,

Why not space? It's certainly possible (I just checked) and it would look
clear I guess:

my_func(1 999 999);


Re: [PHP-DEV] [RFC] Exceptions in the engine

2015-02-18 Thread Nikita Nefedov
On 18 Feb 2015 13:53, Tony Marston tonymars...@hotmail.com wrote:

 Could it be restricted to the current scope? In your example the call to
fopen() exists in the load_data() function and is not in a try ... catch
block within *that* function, so the fact that the call to load_data() is
within a try ... catch block should be irrelevant as it is in a different
scope.

Hi Tony,

This sounds very hacky. If you want exceptions with file/stream functions I
suggest you to find some open library out there that can handle your user
case or you can use SplFileObject.


Re: [PHP-DEV] [VOTE] Scalar Type Hints

2015-02-13 Thread Nikita Nefedov
On 13 Feb 2015 19:37, Benjamin Eberlei kont...@beberlei.de wrote:

 Wait i almost forgot, it *does* have an effect on me, especially around
 callback handling:

 https://gist.github.com/schmittjoh/778e044deacc6f1fe516

 Essentially callbacks are evaluated in the mode they are called in, not in
 the one they are defined.


You're presenting it like this is a wrong behavior whereas it's expectable
to work like this.

One thing php will definitely lack especially after/if this RFC gets
accepted is callback signature type hints, but maybe we'll see them in 7.x


Re: [PHP-DEV][RFC][VOTE] Group Use Declarations

2015-02-13 Thread Nikita Nefedov
On 13 Feb 2015 22:31, Lester Caine les...@lsces.co.uk wrote:
 Can't we restore the simple way of working in PHP7
 where it does not need to wrap around other things quite so closely?

Hi Lester,

This way if doing things on php didn't go anywhere, people just stopped
using it because they saw better alternatives.


Re: [PHP-DEV] [VOTE] Scalar Type Hints

2015-02-12 Thread Nikita Nefedov
Hi,

2015-02-12 18:31 GMT+04:00 Andrea Faulds a...@ajf.me:

 Hi Pavel,

  On 12 Feb 2015, at 13:48, Pavel Kouřil pajou...@gmail.com wrote:
 
  C# does have dynamic typing.

 No it doesn’t, it’s a statically-typed language. I don’t understand why
 you say it has dynamic typing - there is some limited dynamism in parts,
 but I don’t think it affects what we’re talking about. Dynamic typing and
 polymorphism aren’t the same.


 C# actually supports dynamic typing with a dynamic keyword [1]. But it
really doesn't mean that having method overloading in a dynamic language is
a good idea... C#, although it has a full ability to support dynamic
typing, is not usually used in this fashion. To understand why it's not the
best idea to use dynamic types with overloading you can just google C#
dynamic type with overloading site:stackoverflow.com.

Another great deal in this question is performance, I think this subject
was brought up a plenty of times in this ML and it was pointed out a couple
of times that overloading even if doable at some point, would harm
performance of method calls, which are already one of the slowest (if not
the slowest) OPs in the engine. Languages like C# are usually able to
resolve method references at compile time (unless virtual methods are used,
even then it's only a matter of choosing right method from hierarchy not
from all the overloaded variants).

[1] https://msdn.microsoft.com/en-us/library/dd264736.aspx


Re: [PHP-DEV] [VOTE] Scalar Type Hints

2015-02-11 Thread Nikita Nefedov
On 11 Feb 2015 09:38, Rasmus Lerdorf ras...@lerdorf.com wrote:

 On 02/10/2015 07:57 PM, Xinchen Hui wrote:
  am I wrong?!
  seems I am wrong with this, it's a false alarm...  it can restore
automatically.

 Yeah, declare() doesn't span files so that isn't a problem.

 My worry is still the lack of type coercion for internal calls. I tested
 it on some apps and it will take quite a bit of tedious and rather
 useless effort to fix these to run in strict mode. Some examples of
 common things that are fatal errors in strict mode:

   ini_set('precision', 14);

   ini_set('display_errors', 1);

   ini_set('display_errors', true);

   ok, not common, but tan(4/2) fatal, tan(5/2) no error

   Wordpress has this function, spot the error:

   function add_magic_quotes( $array ) {
 foreach ( (array) $array as $k = $v ) {
 if ( is_array( $v ) ) {
 $array[$k] = add_magic_quotes( $v );
 } else {
 $array[$k] = addslashes( $v );
 }
 }
 return $array;
   }

   $v may not always be a string (it died with a float for me), so the
   fix is to cast:

 $array[$k] = addslashes( (string)$v );

   Also from Wordpress:

   $formatted = number_format( $number, absint( $decimals ),
 $wp_locale-number_format['decimal_point'],
 $wp_locale-number_format['thousands_sep'] );

   Here number_format() is expecting a float but $number is a string. So
   again, the only real fix is to cast.

   And in Drupal8 *without turning on strict*:

   use Drupal\Component\Utility\String;

   it dies with: Fatal error: string cannot be used as a class name in
 /var/www/drupal/core/includes/bootstrap.inc on line 11

   That String class is everywhere in Drupal. They are going to have a
   fun time with that. See

https://gist.githubusercontent.com/anonymous/d9252deeeb2aae1a5af5/raw/053155130d22551b1404d0a9b94e27424544b6d1/gistfile1

   From Geeklog:

   if (strtolower($topic) != strtolower($archivetid)) {
 $sql .=  AND ta.tid != '{$archivetid}' ;
   }

   $topic can be null there. Looking at the logic, not really a bug,
   just a natural reliance on null being coerced to 

   Also from Geeklog:

 if( empty( $date )) {
 // Date is empty, get current date/time
 $stamp = time();
 } else if( is_numeric( $date )) {
 // This is a timestamp
 $stamp = $date;
 } else {
 // This is a string representation of a date/time
 $stamp = strtotime( $date );
 }
 // Format the date
 $date = strftime( $dateformat, $stamp );

 strftime() expects an integer for the timestamp there, but as the
 above logic shows, they are expecting a numeric string to be fine.
 No bug, just another forced cast.

 And another number_format() instance where arg1 is not necessarily
 a float. Obviously not a bug, so we have to cast again:

 return number_format( $number, $dc, $ds, $ts );

 In Opencart:

 $this-image = imagecreatetruecolor($width, $height);
 imagecreatetruecolor() expects parameter 1 to be integer, string
 given in /var/www/opencart/system/library/image.php on line 89

 You could argue this is a bug, I guess, but the width and height are
 coming from a database and are integers in the db, but since the db
 returns strings. Another cast...

 I was genuinely hoping to find some bugs with this exercise. I suppose
 it is because I did it on mature projects and at this stage those sorts
 of bugs have already been fixed. But I still fear that people are going
 to want to be enable strictness everywhere and then they will quickly
 learn that they better cast stuff to be safe which makes the whole thing
 rather pointless. And I feel pretty sorry for the Drupal folks. That
 list of 1000+ instances of their String class is going to suck to fix.

 -Rasmus


Hi,

I believe all these projects wouldn't even want to enable strict types due
to the nature of their codebase and they probably don't need to, for sure
this feature is not for them...
What about Drupal, if they don't use dynamic instantiation for string
utility class then it can be fixed in most of IDEs out there with their
rename class feature. Plus keywords reservation is a matter of another
vote (the last one in the RFC) that can succeed even if type hints don't
pass.


Re: [PHP-DEV] Allow arbitrary expressions when using instanceof operator

2014-11-06 Thread Nikita Nefedov
On Thu, 06 Nov 2014 13:01:52 +0400, Stas Malyshev smalys...@sugarcrm.com  
wrote:



Hi!

What I want to implement is the ability to allow arbitrary expressions  
on

the second operand, so instead of having to write something like this:


I'm afraid there's a problem with this. Arbitrary expressions include
constants, right? So what this means:

var_dump($foo instanceof Bar);

is it checking $foo for being instance of class Bar (that's what is
happening now) or is it taking the value of the constant Bar (whatever
it is) - since constant is an expression - and using it as a class name
and then checking if $foo is an instance of that class?

You could of course require the expression to always be enclosed in (),
but that produces weird syntax where some forms of instanceof work
without () and some only with (). Given that you can easily assign your
value to a variable, is it worth it?

Also, you can always use is_a($foo, $bar-getClassName()).



Hey Stas,

You're right about parenthesis - they are required to use expressions.  
Basically when you're in parenthesis - it will only mean that it's an  
expression, otherwise it's a direct class reference. It could be worked  
around by creating a new class of expression (on parser level, say  
expr_not_single_const or anyting like that) that would match any  
expression except constant references, but that's too much I guess.


Also one thing not mentioned in the initial letter - this will also allow  
you to use expressions for new operator in the same way: `new  
(str_replace('/', '\\', $classPath))()` - just an example.


I would say that it's just not logical to have some operator that can  
accept dynamic (runtime-defined) value but not an expression.


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



Re: [PHP-DEV] RFC: Return Types Update

2014-10-16 Thread Nikita Nefedov

On Thu, 16 Oct 2014 18:39:06 +0400, Davey Shafik da...@php.net wrote:

I very much like this — though I would say it was dependent on the  
nullable

types RFC (like splat and variadics were codependent).

While I would like to see the introduction of a void type, I understand  
and

respect the limitations on the RFC.

However, one thing that I do think is missing, is the equivalent of Hacks
`$this` return type. You have `self` and `parent`, but I think without a
`static` equivalent you can break things:

class foo {
 static public function instanceOf(): self {
   return new static();
 }
}

class bar extends foo { }

foo::instanceOf(); // new foo, this is fine, returns `self`.
bar::instanceOf(); // new bar, no longer `self`


Hi,

bar is considered as instance of foo so shouldn't be any problem.  
Otherwise it would break LSP


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



Re: [PHP-DEV] [RFC] Closure::call and Function Referencing as Closures

2014-08-03 Thread Nikita Nefedov

Hey Andrea,

I really love function referencing RFC, this is something I miss in PHP  
and would I have a voting right I'd would +1 even in this state of it.
But I dislike a bit the fact that we start to use Closure for everything,  
I really wish we had a dedicated type for functions (read functions as a  
first-class citizens).



On Mon, 04 Aug 2014 01:50:55 +0400, Andrea Faulds a...@ajf.me wrote:


Good evening,

I am proposing two new RFCs. As they are both inter-related and  
complementary, with the second having the first as a prerequisite, I’m  
making just a single email to cover both:


https://wiki.php.net/rfc/closure_apply
https://wiki.php.net/rfc/function_referencing

Both have written, tested and working patches aimed for master.

Thoughts appreciated, thanks.
--
Andrea Faulds
http://ajf.me/





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


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



Re: [PHP-DEV] [RFC] Escaping RFC for PHP Core - Updates?

2013-09-07 Thread Nikita Nefedov
On Sat, 07 Sep 2013 20:08:45 +0400, Michael John Burgess  
mich...@mjburgess.co.uk wrote:



On 07/09/2013 15:41, Levi Morrison wrote:

It looks nicer than Escaper::escapeJs(), Escaper::escapeHtml(), etc.

Any comments?



Please, don't go down this route. You do not want one class to escape  
all

kinds of data; delegate each type of escaping to its own class:

JavaScriptEscaper-escape();
PhpEscaper-escape();
HtmlEscaper-escape();
HtmlAttributeEscaper-escape();

I should not have to defend this but I am willing to explain in more  
detail

if someone would like me to.




There doesnt need to be any object-oriented version for this problem.  
It's a series of pure functions. Wraping them in one or more classes  
adds nothing.


Michael



Hi,

Wrapping those functions in methods means they can be extended in child  
classes. So suppose you have some library that takes object of type  
Spl_Escaper and uses its methods for escaping some data. Now if you will  
need some additional escaping you just need to make child class for  
Spl_Escaper and override methods which behavior you need to change. This  
can't be done with pure functions (in PHP).


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



Re: [PHP-DEV] RFC: Protocol Type Hinting

2013-06-26 Thread Nikita Nefedov

Hi,

On Wed, 26 Jun 2013 02:57:46 +0400, Stas Malyshev smalys...@sugarcrm.com  
wrote:



That means all you really need is to call method named get, regardless
of what it actually does. Usually the code doesn't work this way - you
expect something to actually happen if you call get(), something
specific. Interface ensures whoever wrote that object acknowledged that
this is what he wants too.


But you (as a library dev) still have interfaces. You still use them.

This discussion got really big in a short period of time, but we all know  
all this change does is gives us an ability to not write additional code.  
Some people already stated it - you just won't need to create adapters and  
it's cool.
There's a lot of cases where you need to wire to different libraries and  
for that matter you create THIRD library and call it something like  
%lib1-name%%lib2-name%Adapter where you, in the best case, should create  
classes that inherit from some lib1's or lib2's classes (and just add  
implements Lib2Interface), or if there's some static methods - you are  
forced to create decorator which implements needed interfaces - and that  
is what will give a far more overhead than some runtime engine-level  
checks.


What about static analysis, it just lays on YOUR shoulders, if you so want  
static analysis to work properly you just write code which implements  
interfaces. But if it's fine for you, then it's fine, it's easy.


PS sorry for caps in some places

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



Re: [PHP-DEV] RFC: Protocol Type Hinting

2013-06-25 Thread Nikita Nefedov
On Tue, 25 Jun 2013 19:57:15 +0400, Anthony Ferrara ircmax...@gmail.com  
wrote:



Hey all,

I want to throw out this draft RFC to get the concept floating around and
get feedback early.

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

There are still open questions, and a more complete (and cleaner)
implementation will be needed before officially proposing it, but I  
wanted

to get the concept out as soon as possible.

What do you think?

Thanks!

Anthony


Hey,

That's great, just great, I have no more words :3

By looking at the diff I see it will only work for type-hints in  
functions/methods. Could we also see something like $var instanceof  
ProtoInterface? I fear it can't be done this way because of parser  
limitations, but I believe this feature would be as useful as type-hinting  
in functions.


And again, that's great :)

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



Re: [PHP-DEV] a couple of thoughts on the DateTime type debate

2013-04-04 Thread Nikita Nefedov
On Thu, 04 Apr 2013 19:13:54 +0400, Rasmus Schultz ras...@mindplay.dk  
wrote:



I've been pondering this issue for a while now, and I keep reaching the
same conclusion, so I'm going to just briefly share what I think.

In my opinion, the real issue is not poor design of the DateTime class -  
it

works as you would expect classes and objects to work, in the sense that
when you make changes (adding, subtracting, changing the timezone) you're
making changes to the instance.

I can't help but think that the real underlying issue, is the fact that  
you

really want value-types and not objects/classes for something like this -
and we only have a few value-types in php, namely the scalar types (int,
string, float, bool) and arrays.

If you've ever attempted to build an object-abstraction for other
value-types, such as colors, URLs (or routes), e-mail addresses, etc. -
you've faced the same issues: when somebody increases the saturation of  
an

RGB color object, do you change the RGB values, or return a new color
instance? Questions like this stem from the fact that what you really
wanted for something as self-contained as a color or URL, is not an  
object,

but a value-type.

I don't tend to like solutions that solve one isolated problem, when the
whole class of problems could potentially be address - hearing about
another DateTime type makes my skin crawl, in particular because it
introduces all manner of issues with current APIs  that most likely  
already

depend on the existing DateTime type. Even coming up with a reasonably
descriptive (yet practical) name for this class, is difficult - which to  
me

indicates a contrived attempt to extend something that only needs to be
extended for technical (as opposed to functional) reasons.

Please consider addressing the real underlying issue: the need for
value-types.

Off the top of my head, I'm thinking this could be addressed by  
introducing

a new keyword for value-types, interchangeable with class, for example
value.

Value-types would work syntactically like classes and objects. But
internally they would work like arrays, meaning they are always passed by
value.

If this could be implemented in such a way that value objects were  
actually
internally implemented as arrays, we would get all the benefits of  
arrays -

mainly that they would be passed by value, but would not physically be
copied until modified.

It seems to me, that really is precisely the behavior you want for
something like a date/time, color, URL, e-mail, etc. - in many frameworks
and libraries, this behavior is actually emulated, by using arrays to
represent colors, routes, etc., in order to be able to treat them like
value-types, but with the enormous downside of having to know which
value-type is represented by an array, typically relying on static
helper-methods to modify their properties, and with no chance of any IDE
support.

Just putting that on the table...

- Rasmus Schultz


Hi,

this is great idea, I thought about it lately.
Though I think it should be called struct like in other other languages.
And it would be very useful if we could declare structs in-place (it's  
useful when dealing with some data-proccessing and all you want is just  
strong-typing but without the need for declaring a whole new class in a  
new file, etc).

But this is a very big feature and I doubt it will get any support :(

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



Re: [PHP-DEV] DateTimeImmutable

2013-03-28 Thread Nikita Nefedov

On Thu, 28 Mar 2013 13:04:44 +0400, Lars Strojny l...@strojny.net wrote:


Hi Derick,

Am 27.03.2013 um 21:53 schrieb Derick Rethans der...@php.net:


On Tue, 26 Mar 2013, Michael Wallner wrote:


providing DateTimeImmutable as a sibling to DateTime.


That's fine with me, but I am not having the time to work on a patch
right now.


Happens. Let’s revert it till somebody finds some time to do it. Could  
you revert it?


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



Hi,

Sorry, maybe I missed something, but what the consensus did we achieve  
here?
Make an interface? Or maybe make an abstract class with constructor, late  
static binded fabric methods (which btw could solve problems with making  
custom datetime class in userland), and some of the methods like diff and  
so on? Or maybe something else?


PS I think I can make a patch on these weekends.

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



Re: [PHP-DEV] Could we kill call_user_func?

2013-03-18 Thread Nikita Nefedov

On Mon, 18 Mar 2013 19:03:41 +0400, Julien Pauli jpa...@php.net wrote:

On Mon, Mar 18, 2013 at 3:33 PM, Anthony Ferrara  
ircmax...@gmail.comwrote:



Angel,

On 18/03/13 14:04, Julien Pauli wrote:

 Also, AFAIR, call_user_func() doesn't work with functions using
 references in args. Julien.Pauli
AFAIK it does.
Do you have an example where it doesn't?



It definitely does not:

http://3v4l.org/C8Kme

And if you try call-time-pass-by-reference, it gets worse:

http://3v4l.org/pI89l


Yeah, that's what I remembered. call_user_func() is not exactly the same  
as

calling the function, when references come to scene, it just wont work.

Same with _array() implementation.

Julien.Pauli


call_user_func_array will work ok. This is the only call_user_func problem.

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



Re: [PHP-DEV] feature request : easy shared memory

2013-03-14 Thread Nikita Nefedov

On Thu, 14 Mar 2013 07:05:03 -, rene7705 rene7...@gmail.com wrote:


Hi.

I'd like to build a replacement for SQL (yes, talk about an ambitious
project! ;), because the constant transferal of data in and out of SQL  
from

Javascript (where everything might as well be object-oriented and
hierarchial) is a pain in the neck.

But in order to do so, I'd very much like PHP (the server still controls
the data after all) to support shared memory efficiently.

Something like

sharedmem $bigNestedArray; // $bigNestedArray would be shared accross the
entire server and all CPUs on it.

as you now have

global $bigNestedArray;

would be ideal.

I bet this would be useful for a host of other applications as well, and
fairly easy to implement.

I'm an application programmer by trade, or I would hack this in myself.

I'd much rather see the PHP development team develop this in properly. I
don't think it would require much time, as OS-level shared memory has  
been

easy to implement since the 1990s.

Please put this on the agenda, and get back to us in this thread as to  
when

this will be available.


Hi,

You can already do it using APC's apc_store() and apc_fetch() functions  
which let you use shared memory. But of course you should 'commit' every  
change of the fetched variable.


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



[PHP-DEV] Should sessions override user sent headers?

2013-03-06 Thread Nikita Nefedov

Hi,

so I stumbled upon this bug report: https://bugs.php.net/bug.php?id=64357

It's fairly easily fixable, but I don't know if it's even a bug... The  
problem here: sessions always send Expire header (except for  
private_no_expire), so if user (php user) sent Expire header before  
session_start() call, it will be replaced (see  
https://github.com/php/php-src/blob/master/ext/session/session.c#L1066 and  
ADD_HEADER macros for example).


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



Re: [PHP-DEV] I would like to write an RFC for the addition of an internal keyword

2013-02-27 Thread Nikita Nefedov
On Wed, 27 Feb 2013 11:07:06 +0400, Jens Riisom Schultz ibmu...@me.com  
wrote:



Hi,

I just want to get a feel for whether the following idea would be  
instantly rejected (for example I get the feeling that adding keywords  
is a big deal):


Often, when writing frameworks, you need to make public or protected  
functionality or classes which should only be called from inside the  
framework. You CAN ensure this with a lot of ninja tricks and  
debug_backtrace, but it is very cumbersome and often hides your methods  
and properties from class signatures.


Therefore I would propose adding a C# style internal keyword. (  
http://msdn.microsoft.com/en-us/library/7c5ka91b(v=vs.80).aspx )


The idea is, simply, that functions, methods and classes marked as  
internal would only be accessible from within the namespace in which  
they are defined.


For example the following class, namespace Framework; internal class  
Something {}, would only be visible from within the Framework  
namespace.


I have a hunch that this would be relatively easy to implement.

If noone objects I would attempt to create a patch and an RFC.

What do you think?


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



Hi,
I, for one, think it should be solved on the IDE side. I used a lot of  
Doctrine's internal methods lately and if they would be not accessible I  
wouldn't be able to do a lot of things.
Of course internal methods/classes shouldn't be exposed as a part of API,  
but if they exist, I would want to call them *if I know what I'm doing*. I  
think it would be useful if phpdoc had an @internal tag so that IDEs could  
highlight places where you use internal parts of library.


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



Re: [PHP-DEV] Late FQCN resolution using ::class

2013-02-25 Thread Nikita Nefedov
On Mon, 25 Feb 2013 14:00:04 +0400, Jens Riisom Schultz ibmu...@me.com  
wrote:



Hi everybody,

I have read up on this, and done some testing.

First up, my findings with PHP5.5 alpha5:

?php
namespace spacy;

class classy {
public static function fqcn() {
/* This works but is not useful enough: */
//return self::class;

$me = 'classy';

/* This just doesn't work, but I wish it did: */
//return $me::class;

/* This simply does not work as expected: */
return eval(return $me::class;);
/* Output: classy - Expected output: spacy\classy */
}
}
?

I'm trying to late resolve a class name contained in a variable to the  
FQCN. I understand that this is hard (maybe even impossible) with the  
current implementation, because class name resolution happens compile  
time, but eval(return $me::class;) simply returns something that is  
weird.


I guess what I'm trying to ask is whether it would be impossible to  
support late FQCN resolution in any way? It would be very useful for  
frameworks to be able to do this.


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



Hi Jens,

Here's what happened in your code:
When you invoked fqcn(), you created var $me = classy;
Then you tried to invoke this code in eval: return classy::class;
But when php evals code, it's like including another file. So it executes  
the code without any namespace (it's in global namespace), and php didn't  
discover class with name classy (there's only spacy\classy) yet, so it  
tries to resolve all your use statements (but you didn't write any) and  
then just gives you classy, it didn't throw any error just because it  
tried to delay autoloading of this class as far as possible, if would do  
eval(return new $me;) then you would get fatal error.


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



Re: [PHP-DEV] Dropping requirement for `function` keyword for methods in classes/interfaces/etc

2013-02-20 Thread Nikita Nefedov
On 20.02.2013, at 1:42, Sanford Whiteman 
swhitemanlistens-softw...@cypressintegrated.com wrote:

 Seems this would complicate the transplanting of (global) functions
 into (default public) class methods and vice versa. This is a common
 refactoring task -- at least IME -- and before I adjust visibility I
 would expect the function to Just Work.
 
 So this works in a class to define the function:
 
 function my_function() { }
 
 And I expect to be able to pull that out into the global scope as-is.
 
 But if people start using this super-shorthand in the class:
 
 my_function() { }
 
 Then when I pull it out into my function library, I'll get errors.
 
 The reverse is also true: I expect to get a fatal from leaving off a
 semicolon between function_call() and {} but at the top level of a
 class it gets smoothly compiled as a function definition.
 
 Look, I know there are similar cases throughout PHP (and other
 languages) already, but why add more for no (IMO) payoff? Perhaps not
 the most compelling case against this new sugar, but it would suffice
 to stop me from ever using it.

Hi Sandy, it won't complicate you anything.
Global functions remain its requirement for keyword, just methods lose it. And 
it doesn't mean that you can't write
class Foo {
function bar() {}
}

As I said, there are no bc breaks at all. My initial patch doesn't forces you 
to write any keyword, so you are actually can declare a method just with 
foo(){}, but it is absolutely doable, i'm just from my cell phone now.


What about readability - removal of this keyword will make a better readability 
of methods. Instead of
abstract class Foo {
public function make()
{
// some code
}

public abstract function do();
}

You will need to read just
class Foo {
public make()
{
// some code
}

public abstract do();
}

It's not function a keyword who lets you recognize function 
definition/declaration, but it's usually a pair of brackets. This function 
keyword is just noise for now, it doesn't serve any purpose aside from typing 
grep 'function funcname' instead of grep 
'(private|protected|public|abstract|static)funcname' , but, you know, if you 
love shell so much (or are forced to use it) you are probably familiar with 
creating 'shortcuts' for it, scripts or aliases.


Now what I think about all this give the arguments - the thing is - function 
keyword is just redundant. It's like appendix, we just don't need it, there's 
no point in it (yeah, except grepping), and we can drop it without any bc 
breaks, so why don't just do it?
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php



Re: [PHP-DEV] Dropping requirement for `function` keyword for methods in classes/interfaces/etc

2013-02-20 Thread Nikita Nefedov
On Wed, 20 Feb 2013 08:02:36 -, Sanford Whiteman  
swhitemanlistens-softw...@cypressintegrated.com wrote:



While I'm thinking about this (though I should leave it alone): who's
to say that PHP won't some day get inner classes? By deciding the
default inner member of a class will be a function, you're choosing
the one that has a global/procedural equivalent where the short syntax
won't work, instead of leaving the concept unused for the possible
future when:

class myClass {
mySomething { // is equivalent to class mySomething {
(Yes, you could say mySomething(...) { } is a public function and
mySomething { } is an innner class, but you get the idea.)

-- S.




Classes always should be declared with class keyword, because there could  
be ambiguity whether it's class, interface or trait.
Also, I will say it again: as Sara noted, we *really* shouldn't let users  
define methods without any modifiers, like this: class Foo { asd() { echo  
this is parse error; } }


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



Re: [PHP-DEV] Dropping requirement for `function` keyword for methods in classes/interfaces/etc

2013-02-20 Thread Nikita Nefedov
On Wed, 20 Feb 2013 09:59:51 -, Sanford Whiteman  
swhitemanlistens-softw...@cypressintegrated.com wrote:


Classes always should be declared with class keyword, because there  
could

be ambiguity whether it's class, interface or trait.


If only inner classes are allowed in a given PHP version, there's no
ambiguity about whether something{} just inside a a class is an
inner class.

That's the justification for removing function just inside classes,
isn't it? That it's not ambiguous because the only thing as of PHP.now
that can take the form sometype somevisibility something(){} is a
function?

Well, if in PHP.later, the only thing that takes the form sometype
something{} is an inner class, then leaving off the sometype there
is also unambiguous (but also similarly gratuitous).

And if in PHP.later.still you have inner interfaces, then the
unmodified one still defaults to inner class and only a literal
interface something{} is an inner intf.

(I'm attempting a RAA argument but maybe failing)

-- Sandy | FigureOne Support Team




So no you are not saying PHP is not Java or C#. I don't want to touch  
any religious views but it's really funny to read :)


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



Re: [PHP-DEV] [RFC] Short syntax for anonymous functions

2013-02-19 Thread Nikita Nefedov
On Tue, 19 Feb 2013 16:31:39 -, Marcello Duarte mdua...@inviqa.com  
wrote:



On 19 Feb 2013, at 16:29, Morfi wrote:


($n) = { echo $n; }
($n) use ($m) = { echo $n; }


Morfi, the problem pointed out already is when you have no arguments it  
would be the same as the statement block, which would cause BC issues.


Why not () = { echo $n; } then?

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



[PHP-DEV] Dropping requirement for `function` keyword for methods in classes/interfaces/etc

2013-02-19 Thread Nikita Nefedov

Hi!

As someone mentioned in the thread about short syntax for closures, we  
could also drop requirement for `function` keyword when defining/declaring  
methods in classes, interfaces or traits.


I have long noticed how redundant it is. The patch is pretty easy as it  
was with commas :)
It is absolutely backwards compatible (you can use `function` or you can  
not use it). Here's the patch: https://gist.github.com/nikita2206/4988075


If people will welcome this proposal, I would need some karma for making  
RFC.


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



Re: [PHP-DEV] Dropping requirement for `function` keyword for methods in classes/interfaces/etc

2013-02-19 Thread Nikita Nefedov
On Tue, 19 Feb 2013 17:53:40 -, Johannes Schlüter  
johan...@schlueters.de wrote:



I agreed to the conclusion that the function keyword provided a nice
way to grep for functions when handling foreign code and leaving it out
only provides little improvement in less typing.

Please provide new arguments for a new discussion. (That thread was
rather long)

And as a general note I'd like to remind you all about Rasmus' recent
mail: http://news.php.net/php.internals/65894 - In my words: Why not fix
bugs instead of creating new ones?

johannes




Hmm, I agree about grepping, but how often do you do it? Actually, last  
time I grepped php files was half a year ago I think, when I had just ssh  
connection and didn't want to mount sshfs. But usually there's IDEs that  
can statically analyze your code and let you search against huge codebases  
in seconds, I don't want to sound mean, but hey, does anybody greps php  
code?


What about reasoning - of course there's no reasons besides less typing.  
At the moment, usually when I want to define method, I usually already  
know will be in its body so I'm trying to type as fast as I can, and I  
often make some mistake in `public` keyword or `function`, actually it  
happens all the time :) So for me it would be pretty good feature if I  
could write one less word.


I agree with Sara about requirement for explicit declaration of visibility  
attr.


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



Re: [PHP-DEV] Dropping requirement for `function` keyword for methods in classes/interfaces/etc

2013-02-19 Thread Nikita Nefedov
On Tue, 19 Feb 2013 18:02:57 -, Christopher Jones  
christopher.jo...@oracle.com wrote:


What about including a few basic examples aka test cases in your patch?   
If the feature is accepted, you'll need to include a LOT of testcases.


Chris



Hi Chris,

this code could be a basic case (just for the sake of understanding)  
https://gist.github.com/nikita2206/4988665

But I will add an actual tests if it's going to receive some support.

On Tue, 19 Feb 2013 18:41:41 -, Rasmus Lerdorf ras...@lerdorf.com  
wrote:



On 02/19/2013 02:39 PM, Nikita Nefedov wrote:

About 20-30 times every single day.

-Rasmus


Hi Rasmus,

Are you grepping for all the functions or you are grepping just for some  
specific function? If so, you are likely already know what visibility this  
function has, so couldn't you grep for `public %functionName%` instead of  
`function %functionName%`?
At the end, you can always use `grep '(function|public|private|protected)  
functionName' file`, and if it's long to type, you can make sh script, or  
even alias.


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



Re: [PHP-DEV] Dropping requirement for `function` keyword for methods in classes/interfaces/etc

2013-02-19 Thread Nikita Nefedov
On Tue, 19 Feb 2013 19:10:22 -, Rasmus Lerdorf ras...@lerdorf.com  
wrote:



On 02/19/2013 03:07 PM, Nikita Nefedov wrote:


Are you grepping for all the functions or you are grepping just for some
specific function? If so, you are likely already know what visibility
this function has, so couldn't you grep for `public %functionName%`
instead of `function %functionName%`?
At the end, you can always use `grep
'(function|public|private|protected) functionName' file`, and if it's
long to type, you can make sh script, or even alias.


public is the default visibility so it is often left off, so no, I can't
grep for that.

-Rasmus


As Sara noted, we shouldn't let users define methods without modifiers at  
all, so at least public/private/protected will have to be there.


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



Re: [PHP-DEV] - True Annotations

2013-01-09 Thread Nikita Nefedov

No please, two symbols for each side looks ugly.
BTW There's number sign (#) which is, as far as I remember, not used in  
PHP at all. Could be something like:

#JoinColumn(name=..., type=..., ...)
#Foo(Bar())

Or

#Foo(#Bar())

(should we put a annotation-sign in front of a nested annotation?)

On Wed, 09 Jan 2013 17:17:44 +0400, Patrick Schaaf p...@bof.de wrote:


Regarding syntax... Would this work?

|foo|
|bar( |baz| )|

best regards
  Patrick


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



[PHP-DEV] Ruby's symbols

2013-01-05 Thread Nikita Nefedov
I know I shouldn't write Ruby in the subject of a letter for  
php-internals ML, but... Just wanted to ask, is anybody interested in this  
feature in PHP?
You can read about it here:  
http://www.randomhacks.net/articles/2007/01/20/13-ways-of-looking-at-a-ruby-symbol


It can be implemented in PHP as a HashTable where key would be strings and  
values would be unique identifiers (just incrementing long, can be tracked  
with nNextFreeElement).


How it would work in userland?

If it would be proposal, I would divide it on two different (competitive)  
proposals:


First, we could implement it so symbol expression would return an  
associated integer.
(note that symbols are most often used as hash keys in ruby so my examples  
are relying on it)

Example:
$foo = array();
$foo[:bar] = qwerty;

var_dump($foo);
// array(1) {
//  [0] =
//  string(6) qwerty
//}

var_dump(:bar); // int(0)

var_dump(:some_new_symbol); // int(1)

This is the easiest way, and I can implement it. But, it would be hard to  
debug.


The second way - we can implement it as a new variable type, and the main  
thing is that arrays will be able to take variables of symbol type as  
keys, I know it sounds scary but it's not so hard actually.
I will drop the part about new variable type, the main thing is how  
HashTables could work with symbols as keys.
We could change the type of nKeyLength (in Bucket) to signed integer (now  
it's unsigned, I don't think we will miss something from that) and use it  
as a flag: if it's -1 (less than zero) - then we know the symbol was used  
as a key, there will be filled bucket.h member with a symbol identifier.

That way the above code will evaluate so:
$foo = array();
$foo[:bar] = qwerty;

var_dump($foo);
// array(1) {
//  [:bar] =
//  string(6) qwerty
//}

var_dump(:bar); // symbol(:bar)

var_dump(:some_new_symbol); // symbol(:some_new_symbol)

To make it clear, when retrieving an element by symbol from array, these  
steps will be needed:

1. Get symbol identifier (ulong)
2. Get elements from array where bucket.h equals to this identifier
3. Iterate over those elements and find the one that has nKeyLength == -1
(actually we will iterate over pNext/pLast elements)


What symbols can give:
1. More convenient way to use it almost everywhere as a replacement for  
strings and sometimes for constants. There's a lot of code that uses  
arrays as a parameter-stores. For example, here's how you usually define a  
form in Symfony2:

$builder
-add('title', 'text', array(
'label' = 'Album title'
))
-add('title_alias', 'text', array(
'label' = 'Album alias',
'required' = false,
'property_path' = 'properties.titleAlias'
))
-add('comment', 'text', array(
'label' = 'Comment',
'required' = false,
'property_path' = 'properties.comment'
))
-add('labels', 'text', array(
'label' = 'Musical labels',
'required' = false,
'property_path' = 'properties.labels'
))
-add('language', 'text', array(
'required' = false,
'property_path' = 'properties.language'
))
It could be improved this way:
$builder
-add('title', :text, array(
:label = 'Album title'
))
-add('title_alias', :text, array(
:label = 'Album alias',
:required = false,
:property_path = 'properties.titleAlias'
))
-add('comment', :text, array(
:label = 'Comment',
:required = false,
:property_path = 'properties.comment'
))
-add('labels', :text, array(
:label = 'Musical labels',
:required = false,
:property_path = 'properties.labels'
))
-add('language', :text, array(
:required = false,
:property_path = 'properties.language'
))
2. Memory usage reduction. AFAIK, there's a lot of cases like the above  
and the use of symbols would affect on memory usage significantly.
3. Memory leaks. Symbols can't be just garbage collected as, for example  
zvals, it's not possible. But we can do it for every request, so I don't  
think it would be problem.

4. Autocompletion from IDEs.

PS I don't want to call it proposal, despite the fact that this is  
actually a proposal, I'm just not sure it can go as a proposal.


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



Re: [PHP-DEV] Ruby's symbols

2013-01-05 Thread Nikita Nefedov

On Sat, 05 Jan 2013 10:27:01 -, Crocodile crocodil...@gmail.com wrote:Sounds like it could make some sense. However, I've got a question..array(

'label' = 'Comment','required' = false,

'property_path' = 'properties.comment')

is actually equivalent to

array('label' = 'Comment',

'property_path' = 'properties.comment','required' = false,

)(Notice the change in keys order. As long as we just use those arrays as hash maps, we notice no differences).

With symbols, which act as aliases for integer array keys, the situation could be different, right? Or excuse me if I don't get what symbols are (I don't know much about Ruby)

Cheers,Victor

2013/1/5 Nikita Nefedov inefe...@gmail.com

array(
'label' = 'Comment',
'required' = false,
'property_path' = 'properties.comment'
  )
Hi,PHP arrays are always ordered (they actually are doubly-linked lists and hash tables at the same time), so there won't be any change in ordering behavior.

Re: [PHP-DEV] Ruby's symbols

2013-01-05 Thread Nikita Nefedov

On Sat, 05 Jan 2013 12:21:26 -, Nikita Popov nikita@gmail.com wrote:On Sat, Jan 5, 2013 at 3:07 PM, Nikita Nefedov inefe...@gmail.com wrote:

What symbols can give:
1. More convenient way to use it almost everywhere as a replacement for strings and sometimes for constants. There's a lot of code that uses arrays as a parameter-stores. For example, here's how you usually define a form in Symfony2:

$builder
  -add('title', 'text', array(
'label' = 'Album title'
  ))
  -add('title_alias', 'text', array(
'label' = 'Album alias',
'required' = false,
'property_path' = 'properties.titleAlias'
  ))
  -add('comment', 'text', array(
'label' = 'Comment',
'required' = false,
'property_path' = 'properties.comment'
  ))
  -add('labels', 'text', array(
'label' = 'Musical labels',
'required' = false,
'property_path' = 'properties.labels'
  ))
  -add('language', 'text', array(
'required' = false,
'property_path' = 'properties.language'
  ))
It could be improved this way:
$builder
  -add('title', :text, array(
:label = 'Album title'
  ))
  -add('title_alias', :text, array(
:label = 'Album alias',
:required = false,
:property_path = 'properties.titleAlias'
  ))
  -add('comment', :text, array(
:label = 'Comment',
:required = false,
:property_path = 'properties.comment'
  ))
  -add('labels', :text, array(
:label = 'Musical labels',
:required = false,
:property_path = 'properties.labels'
  ))
  -add('language', :text, array(
:required = false,
:property_path = 'properties.language'
  ))
2. Memory usage reduction. AFAIK, there's a lot of cases like the above and the use of symbols would affect on memory usage significantly.
3. Memory leaks. Symbols can't be just garbage collected as, for example zvals, it's not possible. But we can do it for every request, so I don't think it would be problem.
4. Autocompletion from IDEs.Hi Nikita!I don't quite understand what those symbols would actually be good for. If it's just for saving exactly one character for array keys (:foo vs "foo"), then this isn't worth it. If this is about memory savings, then I don't think it will help at all. PHP uses interned strings, so all those "label" etc strings in your above example actually use the same string value. The hash for those strings is also precomputed, so symbol don't have a performance advantage either. Regarding your fourth point, autocompletion is available for string array keys at least in PhpStorm and I guess also in other IDEs.
So, I don't yet really get what the point behind the symbols is.Thanks,Nikita
Hi, yes, you are right about interned strings, I didn't know it.Actually my personal opinion is that strings should be used to store data (as values), not to retrieve it (not as keys). But strings are more developer-friendly than anything else (because you don't need to define new constant or new enumerable member for adding new parameter on receiving side, and you always see what this parameter is about). So you can see Symbols as enumerable that don't need to be initialized. There's actually no technical reason behind that.Though there would be a little speed-up because with Symbols array's Buckets will keep numeric key, so instead of memcmp you will need to just compare two longs when retrieving element.Actually this is looks a little bad now, AFAIK this is what happens when you trying to receive value from array by string key:Calling zend_new_interned_string_int for interning or getting already interned same string, receiving pointer to the stored string from it:Hash the string (O(n))Retrieve bucket from arBucketsFind needed bucket by iterating over all retrieved buckets (over *pLast) and comparing its keys with memcmpIf found - return pointer to string, else create new bucket...Now that we have an interned string, we can try to retrieve value from array with string:Hash the string again (O(n))Retrieve bucket by hash fro arBucketsAnd again memcmp used for comparing stringsThis could be improved with Symbols, so that you won't need hash string twice and use memcmp.BTW do we really need a doubly linked list for interned strings (pListLast, pListNext) and all the extra members from HashTable/Bucket that needed for arrays? I know this is offtopic and these structs are used everywhere in PHP (because of DRY), but there are some places like this or class tables where we don't need arrays (PHP's arrays) functionality.

Re: [PHP-DEV] DateTime improvement

2012-12-21 Thread Nikita Nefedov
I don't think it would be ok to move just DateTimeImmutable to the  
namespace.
There were proposal to move all the php functions and classes in  
namespaces, so that for example str_replace() could be \Str\replace() and  
array_map() could be \Array\map() and so on.


On Fri, 21 Dec 2012 12:33:04 +0400, Christian Stoller stol...@leonex.de  
wrote:


What about putting the new DateTimeImmutable (or whatever it will be  
called) into a PHP namespace?

Something like \PHP\Foobar\DateTimeImmutable

Is it generally planned to use namespaces for PHP classes? In my opinion  
it would be nice if the SPL and other classes would be put into such a  
namespace, too. Are there any plans to do that?



Christian Stoller


-Original Message-
From: Peter Cowburn [mailto:petercowb...@gmail.com]
Sent: Friday, December 21, 2012 1:14 AM
To: Lazare Inepologlou
Cc: Larry Garfield; internals@lists.php.net
Subject: Re: [PHP-DEV] DateTime improvement

On 20 December 2012 20:06, Lazare Inepologlou linep...@gmail.com wrote:

Of course, I have no idea if anyone in userspace is using

DateTimeImmutable...

Well, it seems unlikely, unless he is Yoda or French.

I mean, in English, it is common to put the adjective in front of the  
noun,

isn't it?


Class names aren't particularly subject, too strictly, to English
grammar rules.  Besides, the coding standards [1] dictate the class
name should be prefixed with the 'parent set' (e.g. extension name),
which in this case is not Immutable.

[1] https://github.com/php/php-src/blob/master/CODING_STANDARDS#L152



Lazare INEPOLOGLOU
Ingénieur Logiciel




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



Re: [PHP-DEV] DateTime improvement

2012-12-11 Thread Nikita Nefedov

Hi!


Date is immutable, but there's no reason why date object should be able
to represent only one date. Reference to Java is not exactly applicable
here, as many problems existing in Java (thread safety, long-living
object references, etc.) do not exist in PHP.


Say we have a blog post entity, it looks like this:
Post Object
(
[title] = Qwerty
[body] = Lorem ipsum
[craetedAt] = DateTime Object
(
[date] = 2010-10-23 00:00:00
[timezone_type] = 3
[timezone] = Europe/Moscow
)
)

Now we have some third-party service that we need to use to send our post  
somewhere, it has a method that accepts title, body and DateTime object  
when the post was created. So we pass our DateTime object to that method  
and it can do with that object whatever it wants. When our script ends, it  
tries to persist all changes to entities and this date will end up in the  
database.
Or we can watch at that problem from ORM's side - when it fetches rows and  
maps them to objects, it should remember original state of that data, so  
it can distinguish what objects need to be UPDATE-d in database in the  
end. So there's to ways for ORM to think about dates - as  
strings/timestamps (it could be database's representation of date like  
2010-10-23 or just integer with timestamp) or it could be objects of  
DateTime. More efficient and logical way would be objects, but that way  
you must aware users that they shouldn't modify values of DateTime  
objects, and instead they should create new instance when they want to  
change value of datetime type. And it's just bad that there could be  
situations when the entity will represent different data, after  
persisting, than database.



It does not - if you don't need it mutable, don't use modify() or
override modify() with method that would clone the object and return
modified clone. This can easily be done in userspace if you require an
immutable object, which most of the users actually do not.


I was speaking not about modify() but about add() and sub(). Actually I  
don't like these two methods (plus and minus) that I proposed too, but how  
can we solve this problem differently?


What about user-land implementation - there's one problem: I can't just  
extend DateTime object, because it has factory methods like  
createFromFormat, so I need to use decorator pattern and from that point  
hell begins.



Timestamp doesn't need any timelib parsing AFAIK, but YMD certainly does
- you need to calculate the actual timestamp according to current
timezone, etc.


I meant I must either call create new DateTime and pass to constructor  
timestamp string starting with @ (and there would be parsing involved) or  
call createFromFormat and pass U as second parameter and timestamp as  
first one.



DateTime objects can be compared directly, why do you think you can
compare only timestamps?


My fault, didn't know about that.

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



Re: [PHP-DEV] Improve DateTime Class

2012-12-10 Thread Nikita Nefedov
On Mon, 10 Dec 2012 16:09:36 +0400, Christian Stoller stol...@leonex.de  
wrote:



Hi internals,

what do you think about improving the modification functionality of the  
DateTime class. I always get a cold shiver, when I write something like  
this:

?php
$date = new DateTime()
$date-modify(‘+15 day’);

In my opinion it would be nicer if one could write:
$date-modify(15, DateTime::INTERVAL_DAY); // for adding 15 days
$date-modify(-15, DateTime::INTERVAL_DAY); // for subtracting 15 days

Even better would be to have methods like addDays(), addMonths(), etc.

This would make it cleaner and more readable. You do not have to do  
something like this:


$date = new DateTime();
$date-modify(getDaysToAddMethod() .  day); // I am not sure if a '+'  
sign is needed if the value is positive


And it is fully backward compatible.

Best regards
Christian



Hi,

I think we shouldn't improve this functionality because modifying date  
object in the first place is bad idea. Think about it as monatomic object,  
like integer, you can't create new integer object of 42 and then just  
change its value - it will be another object.


As a workaround you could create your own date class, extend it from  
\DateTime and add what you want.


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



[PHP-DEV] DateTime improvement

2012-12-10 Thread Nikita Nefedov
So there had been at least two or three messages (subjects) about DateTime  
object and everytime there was this problem - people tend to take DateTime  
object as mutable object and it really is.
As long as we know, it's not so good - date is immutable by nature. I  
don't want to write here why it's so, I will just throw this link:  
http://www.ibm.com/developerworks/java/library/j-jtp02183/index.html


I don't want to change any existing functionality, because some people  
already use it, but I just wanted to point out that current DateTime class  
is forcing people to think about it as mutable.
My main concerns are DateTime#add() and DateTime#sub(). The problem is -  
they both change current object and return it.
I think we could add methods to DateTime like add() and sub(), let's say  
plus() and minus(), but they would behave differently in the way that they  
would return new DateTime objects and won't change current object.


Here's gist to make it clear: https://gist.github.com/4250785

Also, there's methods compareTo, createFromTimestamp and createFromDay, it  
could be another proposal. I think we are very often create DateTime  
objects just from timestamp or year-month-day. So we could introduce this  
methods that could not rely on timelib's parsing, and instead just take  
numbers directly.
And I think DateTime lack comparing method. For now I can compare DateTime  
objects only by getting their timestamps, but I though that the idea of  
DateTime was to go away from using timestamps and instead use well thought  
out api.
Anyway, I think this three methods should be considered as another  
proposal (because they are solve different problems).


Even if this proposal doesn't go far, I think we should do something with  
DateTime. I think I'm going to create user-land library for dealing with  
some of this problems.

But if it pass, I will make patch.

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



Re: [PHP-DEV] DateTime::modify('now') is ignored, why?

2012-11-26 Thread Nikita Nefedov
On Mon, 26 Nov 2012 15:06:09 +0400, Ivan Enderlin @ Hoa  
ivan.ender...@hoa-project.net wrote:



Hi internals,

I would to modify a \DateTime object to the current time, thus I wrote  
this:


$d = new \DateTime('+1 hour');
$d-modify('now');

It did not work. Why? Because the documentation  
(http://php.net/datetime.formats.relative) says: “Now - this is simply  
ignored”. Really? But the behavior is pretty straightforward isn't?  
“modify to now” means “set to the current date and time and let the  
timezone unchanged”.


Thoughts?
Best regards.



Shouldn't DateTime be immutable? What's the point of DateTime object being  
mutable?
I would include my point about why DateTime should be immutable but I even  
can't come with any points except OO-logic and all I can say is I just  
feel like mutable DateTime is wrong. What you think about it?


PS I'm not Nikita Popov (aka nikic) :)

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



Re: [PHP-DEV] Changing the default value of true for CURLOPT_SSL_VERIFYHOST

2012-10-25 Thread Nikita Nefedov
CURLOPT_SSL_VERIFYHOST - this option just sounds like should I verify  
host?, when it must sound like what verifying strategy should I use?


On Thu, 25 Oct 2012 10:19:24 +0400, Adam Harvey ahar...@php.net wrote:


On 25 October 2012 13:46, JJ ja...@php.net wrote:

On Wed, Oct 24, 2012 at 10:34 PM, Sherif Ramadan
theanomaly...@gmail.com wrote:

I understand there are people out there that don't read the
documentation and aren't aware of the difference between
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); and curl_setopt($ch,
CURLOPT_SSL_VERIFYHOST, true); but still... I don't think this is a
good idea either.


I highly doubt code that sets CURLOPT_SSL_VERIFYHOST = true meant to
imply CURLOPT_SSL_VERIFYHOST = 1...which essentially bypasses host
verification.


They may have, even in spite of it being a bad idea, since that's how
boolean → integer conversion works in PHP. I don't think we can assume
that every single person who's written that line of code didn't check
whether CURLOPT_SSL_VERIFYHOST was a boolean or integer option.


According to libcurl, CURLOPT_SSL_VERIFYHOST = 1 is not ordinarily a
useful setting.


I agree, but I don't think we can start arbitrarily changing well
defined type conversion behaviour for one corner case. The
CURLOPT_SSL_VERIFYHOST option has been documented as expecting integer
0, 1 or 2 since at least April 2002 (and probably quite a bit earlier
than that), complete with the meanings of each value — there's only so
much we can do to protect developers from themselves. (In fairness,
the wording strongly recommending using option 2 only came in last
August thanks to Ilia, but nobody should have been treating the option
as a boolean option to start with.)

Fundamentally, it's a bad API on the part of curl, but that's a
separate issue. There's nothing stopping somebody proposing a saner
API on top of libcurl (as Anthony did recently with the password
hashing API atop crypt()).

In summary, I'm against changing ext/curl here.

I do have a couple of specific comments on elements of the patch
itself in the event that the changed behaviour is wanted, but I'll
post those on GitHub, since it's probably a better UI for that sort of
granular discussion.

Adam

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


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



Re: [PHP-DEV] Generics proposal

2012-10-21 Thread Nikita Nefedov
No, this is useful in any OOP-language where there is such thing as type,  
and people need to validate types.
I unerstand what you are saying about PHP being an easy language, but in  
opinion if you don't want to use that feature you can not use it, as you  
can not use typehinting in functions for example.




Hi Nikita,

What you're asking for is useful in other languages, but it doesn't match
the style of PHP which is to be a quick and easy type-less scripting
language.

What you're proposing is clearly more suited to something like Java or  
C#,

but doesn't really belong here.

I'd also hate to see this anywhere near PHP.

Many thanks,
Paul.

On Sat, Oct 20, 2012 at 11:10 PM, Marco Pivetta ocram...@gmail.com  
wrote:



On 20 October 2012 23:09, Michael Stowe mikegst...@gmail.com wrote:

 I see what you're trying to do but not a big fan of how it's being
 implemented in the example given.

 - Mike

 Sent from my iPhone

 On Oct 20, 2012, at 4:02 PM, Rasmus Lerdorf ras...@lerdorf.com  
wrote:


  On 10/20/2012 01:59 PM, Nikita wrote:
  Hello, list. I want to propose generics. For those, who don't know
what
 it is, here's example: say we have a Comment class, that has a method
 getBody. Also we have Collection class, that implements Traversable.  
Now,
 if I want to validate all insertions into collection of comments, I  
would

 need to create CommentCollection class, extend it from Collection, and
 override all the methods that are dealing with adding new elements to
 collection. Moreover, I can't have any hints from my IDE about type of
 collection's elements, so if I'll have code like this:
  foreach ($commentCollection as $comment) {
 $comment-getBody();
  }
  There will be no way for IDE to know, of what type that object will
be.
 
  But there's how I could solve my problem with generics:
  class CollectionT implements Traversable
  {
 ...
 public function add(T $element){}
  }
  $collection = new CollectionComment();
 
  $collection-add(new Comment());
 
  $collection-add(that will be error);
 
  Actually, that's, again, all about type hinting. If we went so far
with
 scalar type hinting, then generics would also be a good addition.
 
  So, what you think?
 
  Personally I would hate to see this anywhere near PHP.
 
  -Rasmus
 
 
  --
  PHP Internals - PHP Runtime Development Mailing List
  To unsubscribe, visit: http://www.php.net/unsub.php
 

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


Well, the example just shows what I've already got used to when working
with Java.
I like it and it would be of great help to me (especially in reducing  
the

amount of code to be tested), but there's a lot more around that, like
multiple generic types (new MapComment, User()) and how reflection  
would

deal with it...

Marco Pivetta

http://twitter.com/Ocramius

http://ocramius.github.com/


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



Re: [PHP-DEV] Generics proposal

2012-10-21 Thread Nikita Nefedov
I actually don't have much experience with generics, so won't argue about  
their readability, but this article is all about Java's implementation of  
generics, so I don't know how much sense this article gives in that  
context.
But it's ok, I see just one person that supported proposal. I think case  
closed.


I see what you are trying to achieve, but I hope this will never make  
into
PHP mainly for impact on readability.  I'd like to quote Eric Armstrong,  
a

passionate Java/Ruby dev:


I decry their very existence. They are the ultimate condemnation of

static

type checking--because their very addition has virtually destroyed both

the

readability and elegance of the language.
To make my case, let's start with a quasi-mathematical definition of

elegance.

In my view, elegance is a function of power and simplicity. Power is

measured

by how much you can do. Simplicity is the inverse of the number of

characters

it takes to achieve the result. So more power with fewer characters

equals

elegance


http://www.artima.com/weblogs/viewpost.jsp?thread=299081

__

I question the need to validate types part. I'd say you're better off  
using a completely different language if you want to use strong typing.  
For PHP: Embrace duck typing, write less boiler-plate code (thus  
reducing the need for smart IDE) and be happy :-)


We have typehints, that was my point here.

That's the same as saying you can ignore most of the C++ feature and  
that will make it a simple language. That's neither true for developers  
nor users of the language.


PHP now is multi-paradigm language (isn't it), so... yep, that's the same  
:)


1) Makes language harder to maintain as there is more (and more complex)  
code implementing it.
2) Makes documentation bigger so users have first to figure out what  
part to read and what part to ignore.
3) Makes it harder to write portable user-land libraries as the  
application and the different libraries might use different (clashing)  
paradigms. See error codes vs. exceptions as an example of this.
4) Makes it harder to have extensions like APC as they have to implement  
more features.

5) Makes it harder to write alternative implementations.


All this points are also applicable to namespaces, [abstract,final]  
classes, interfaces, traits, access modifiers (instead of using `var`),  
etc.
If you would have said, this points in the context of... say... necessity  
of that feature, then yeah, maybe you would be right.


Anyway, as long as almost no one didn't supported, I think we can close  
this discussion.


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