xp-framework/rfc — Issue #3: Core functionality cast()
Author: thekid
Created: 2011-10-17 14:49:32+00:00
State: closed
Labels: framework, obsoleted

Scope of Change
====
Have a cast function which casts objects. Allowed cast directions
are up and down in the class hierarchy, not sideways.

Rationale
====
PHP does not have a built-in casting mechanism for objects. Casting
is usually considered a necessary feature of type safe languages
only, but can be useful in some situations.

Example: Consider the rdbms.sybase.SybaseResultSet class. It is
returned from rdbms.sybase.SybaseConnection::query() and lets you
iterate over the resultset. Say we would like to apply a filter
or function on this resultset and would subclass SybaseResultSet
to achieve this. We would also have to subclass SybaseConnection
to return this new class from its query() method without casting.
With this functionality, we would able to cast the SybaseResultSet
to our specialized version of it.

Functionality
====
Casting can be only performed to a super- or a subclass. Given this
hierarchy

```
+ Object
|
-- + ParentElement
| |
| -- ChildElement
|
-- Foo

```

casting would be available from ChildElement to ParentElement vice
versa, from ParentElement to Object vice versa, from Foo to Object
vice versa but *not* from ParentElement or ChildElement to Foo nor
from Foo to ParentElement or ChildElement.

When an object is cast, all of its member variables should remain
"intact", i.e. not be a copy of the original class' members.

Examples (abbreviated for readability reasons):

```php
elements= elements;
}

// [ ... ]
}

class FilteredListIterator extends ListIterator {
// [ ... ]
}

class ElementList extends Object {
var $elements;

function &iterator() {
return new Iterator($this->elements);
}

// [ ... ]
}

$list= &new List();
with ($i= &cast($list->iterator(), 'FilteredListIterator'); {
$i->setFilter( ... );
while ($i->hasNext()) {
var_dump($i->next());
}
}
?>
```

Dependencies
====
n/a

Related documents
====
http://experiments.xp-framework.net/?people,friebe,cast/test.php

Comments:
====
- friebe, Sat Jan 24 17:39:31 CET 2004
Decide on syntax: cast($object, $type) vs. cast($type, $object). The
latter would be nearer to $cast= (Type)$object; but would change the
existing cast() defined in lang.base.php - so there would have to be
a new function, maybe xp::cast()?