# RFC: class casting to scalar

- Status: Inactive
- Authors: Mark Karpeles <mark.at.hell.ne.jp>
- Date: 2008-11-24
- Version: 1.0
- Original: https://wiki.php.net/rfc/class_casting_to_scalar
- Page: https://externals.io/rfc/class_casting_to_scalar
- More for agents: search with https://externals.io/search.md?q={query} · RFCs at https://externals.io/rfc.md · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

## Discussions on the mailing list

- [RFC: Boxing and Unboxing](https://externals.io/message/44616.md) — started on 2009-07-01, 3 messages
- [\[RFC\] Custom Casting](https://externals.io/message/60523.md) — started on 2012-05-09, 11 messages

---

This RFC covers a way to cast classes to scalar values other than strings.

## Introduction

Currently the Zend Engine provides some magic to methods in classes with defined names, for example \_\_toString() is called when someone attempts to cast a class to a string.

The purpose of this RFC is to propose a way to allow casting to other scalar types (boolean, double, integer).

### Why casting?

For the same reasons as \_\_toString() exists, casting to other types might be needed. Feature requests have been submitted regarding this in the past.

## Possible features/implementations

### Interface or magic method?

Currently two possibilities exists:

- Implementing a new magic method, for example \_\_scalarValue() or \_\_cast() in the Zend Engine.
- Creating a new interface (for example ScalarAccess?) and force the presence of one function (scalarValue()?) which will return the scalar value for this class.

### Pass requested type?

Concern has been raised over the fact of passing the requested value type as parameter to the function, as it could be used to disallow some kinds of cast.

## Proposal and Patch

- Patch for \_\_cast() against PHP 5.2.6: [http://ookoo.org/svn/snip/php-5.2.6\_class\_cast\_func.patch](http://ookoo.org/svn/snip/php-5.2.6_class_cast_func.patch)
- Patch for \_\_cast() against PHP 5.3.0: [http://ookoo.org/svn/snip/php-5.3.0alpha2\_class\_cast\_func.patch](http://ookoo.org/svn/snip/php-5.3.0alpha2_class_cast_func.patch)
- Extension for ScalarAccess interface for PHP 5.2.6: <http://ookoo.org/svn/snip/phpcastable/>

### Rejected Features

- None yet

### Bugs

- When used with math operators, it seems we \*have\* to cast to integer if not explictly requested in the code. TODO: find a way to force our way with a float value if needed

## Changelog

2008-11-24: Initial draft
