|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #50599 Magic method for overriding gettype() results.
Submitted: 2009-12-29 00:35 UTC Modified: 2009-12-29 17:16 UTC
From: jmcentire at gmail dot com Assigned:
Status: Not a bug Package: Feature/Change Request
PHP Version: 5.3.1 OS: Debian
Private report: No CVE-ID: None
 [2009-12-29 00:35 UTC] jmcentire at gmail dot com
I'm modeling my data as objects and would like it to be as transparent 
as possible.  As such, gettype($myObj) should return a type value other 
than 'object.'  Can you implement a magic method __gettype() which 
expects the return value to be a string?

Reproduce code:
From manual page: language.oop5.magic
class MyInt {
    public function __construct ($val){
        $this->val = $val;
    public function __gettype () {
        return 'int';

$foo = new MyInt(5);
$int = (int) 5;

if (gettype($foo) == gettype($int)){
    echo gettype($foo); // Should echo 'int'
} else {
    echo "Fail."

Expected result:
Ideally, the code above would echo "int" as the type of MyInt $foo is 
overridden by the __gettype magic method to be 'int', just as it is for 

Actual result:
The code above will echo "Fail."  You may also need to implement a 
type-agnostic equivalent of __toString() like __return() that does, 

public function __return () {
    return ($this->__gettype()) $this->_value;

This would allow me to compare:

($foo === $int); // This should evaluate to true.


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2009-12-29 12:14 UTC]
gettype should really give the type, your class will always behave differently from an integer (just think about by value and by ref)
 [2009-12-29 17:16 UTC] jmcentire at gmail dot com
To whoever started this bug report(and the note in language.oop5.magic), you are using my email address...please use your own.
PHP Copyright © 2001-2022 The PHP Group
All rights reserved.
Last updated: Wed Jan 26 08:03:33 2022 UTC