开发者

can I extend php types?

e.g.

class 开发者_如何转开发MyFloat extends float {
  function Formatted() {
    return number_format($this->value,2);
  }
}

and later use 123.Formatted?


There is SplFloat for your extension pleasures. However, it is not yet available in current PHP versions. And it won't impact basic language semantics either way. It will always be a separate class. (PHP is what's commonly called an "unpure" OOP language.)

But for "future compatibility", you could choose this name for extension purposes.

if (!class_exists("SplFloat")) { class SplFloat {} }

class MyFloat extends SplFloat {
   ...


I am certain you can't do that, not on float at least.

You could make your own class though...

class MyFloat { 
   private $value;

   public function __construct($value) {
       if ( ! is_float($value)) {
           throw new Exception('Floats only');
       }
       $this->value = $value;
   } 

  public function formatted($places) {
       return number_format($this->value, $places);
  }

  public function get() {
      return $value;
  }
}

PHP just needs a __toInt() magic method :)


I don't believe you can as float is a primitive not a class, but I could be wrong.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜