开发者

Is there a way to have PHP objects to "act" like native types? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Implicit Type Conversion for PHP Classes?

Let's say I want to define my own native types, or just looking to bridge an Object to a native type.

For example, take this class:

class Integer {

 private $num;
  function __construct($number){
   $this->num = $numb开发者_高级运维er;
  }

}

Is there a way I can use this class doing:

$n = new Integer(14);
echo $n+3; //output 17

Thanks!


I can suggest another solution for 5.3. You can implement __invoke() method and write like this:

$n = new Integer(14);
echo $n()+3; //output 17

The full code:

<?php
class Integer {

 private $num;
  function __construct($number){
   $this->num = $number;
  }
  public function __invoke() {
    return $this->num;
  }
}

$n = new Integer(14);
echo $n() + 3; //output 17


PHP doesn't support implicit conversion on custom types or classes, so such constructs won't work. I think the easiest (though boring) way is to implement your own methods in such objects like toInteger, toString, toBoolean, etc. and always call them when you want to perform basic operations.

Like this:

$n = new Integer(14);
echo $n->toInteger() + 3; //output 17


Why not:

class Integer{
    private $Integer;
    function __construct($n){
        $this->Integer = (int)$n;    
    }
    public function __toString()
    {
        return strval($this->Integer);
    }
}

$n = new Integer(14);
$a = strval($n);
echo $a+3; //Ouptups 17
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜