On 1/3/2013 9:33 AM, Steve Clay wrote:
On 1/3/13 5:58 AM, Clint Priest wrote:
class Foo {
public $bar = 2 {
get;
set;
}
}
Consider properties not based on shadowed values:
class Foo {
private $realbar;
public $bar = 2 {
get { return $this->realbar; }
set { $this->realbar = $value; }
}
}
What would be the point of this? Why not just do this:
class Foo {
private $realbar = 2;
public $bar {
get { return $this->realbar; }
set { $this->realbar = $value; }
}
}
Here, initializing the shadow property is useless. It's similar to the
case where you want to have the initial value of a traditional
property be the result of an expression (and you can't because it
would create a chicken-egg problem during construction).
Option 1: The most powerful solution I see is to have an init function
that's implicitly called before first access (and with direct write
access to the shadow property if needed). Consider trying to emulate
the crazy document.cookie API:
class Document {
private $cookieProps;
public $cookie {
get { return /* based on cookieProps */; }
set { /* set some cookieProps */ }
// called implicitly before the first access (not before the
constructor runs)
// and would have direct access to the shadow property.
init { /* set up cookieProps */ }
}
}
Pros: can run any code necessary to initialize the property
Cons: must make a function just to have a default
Option 2: Keep the traditional syntax, but instead of always setting
the shadow property, call the setter with the given initial value
directly before the first access.
Pros: familiar syntax; more expected behavior in some cases
Cons: what if there's no setter?; cannot run arbitrary setup code;
setter can't distinguish between a "user" set and the implicitly set
before first access.
Option 3: A mix of both. The shadow property is always initialized
with the value from the traditional syntax. If needed, you can have an
init that's called before first access.
Pros: For simple shadowed properties, just works as you'd expect and
with familiar syntax; Still allows robust initialization before first
access if needed.
Cons: Author must remember that traditional syntax only useful for
shadow prop.
I like the idea of an init function, but that would have to wait for a
further release I think, or delay this whole project a year.
Adding the ability to specify an = X value to a property with accessors
would be trivial.
Steve Clay
--
-Clint
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php