On 12/11/2017 09:49, Fleshgrinder wrote:
Other languages allow you to have a contract on fields.
class A { const FOO: int = 42; }
class A { final static $foo: int = 42; }
These are basically the same, as you already said. However, I added a
contract to both of them.
Yes, I wondered whether to mention type constraints; certainly the
previous, stalled, proposal would have added them directly on what I was
calling "fields". The more I think about it, though, the more I think a
separate notion of "properties" like C# would be a great way to add new
constraints in a clear way.
Consider "int $foo { public get; private set; }" as defining the following:
- a field which like any other variable could theoretically have any
value, but which will never be accessed except via the property definition
- a getter method with the signature "function(): int"
- a setter method with the signature "function(int $foo): void"
It immediately makes sense why you can't assign by reference (the setter
method doesn't take a reference, only a value). It also makes sense to
have this present in an interface (the implementing class is obliged to
have such a property, but may define explicit getter and setter methods
rather than defaults).
You could then also have syntax for a property with a compile-time value
and no setter, but I'm not sure whether this meets your requirements.
There is one thing that differs for the const
and the field: a const value must be known at compile time, whereas a
field value does not. An important difference!
class A { abstract public const FOO: int; }
class A { abstract public function foo(): int; }
These also look basically the same. The return value of the method,
however, may also be determined at runtime (just like with fields) and
on top of that might change with every invocation.
What I'm not really clear on is *why* the value being known at
compile-time is important to you. Is there some architectural decision
you would make differently based on this guarantee? Are you expecting
the language itself to have some optimisation or different behaviour
based on that guarantee?
Would the ability to mark a function as "pure" (always returning the
same output for the same input) serve the same purpose, since a pure
function with no arguments can be substituted for its return value at
compile time?
abstract class A { abstract static pure function getFoo(): int; }
class B extends A { static pure function getFoo(): int { return 42; } }
class C extends A { static pure function getFoo(): int { return 999; } }
Regards,
--
Rowan Collins
[IMSoP]
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php