dsa4d4789789 2017-07-22 21:56
浏览 73
已采纳

实例化没有显式构造函数的类是否合法?

I recently created two code examples to test how constructors work in php, one with an explicit constructor and other without. Both output was the same.

Is it legal to instantiate a class which has no explicit constructor?

Code with constructor

<?php
class Circle {
      const PI = 3.14;
      public $radius;

//Constructor method 
       public function __construct($r) {
             $this->radius = $r;
       }

       public function calculate() {
             return 2 * self::PI * $this->radius;
       }
}

//Argument passed during instantiating
 $C = new Circle(7);
 echo ("Circumference of Circle: ".$C->calculate());
?>

Code without Constructor

 <?php
   class Circle {
        const PI = 3.14;
        public $radius;

    //Non-ideal class mutation method 
            public function calculate($r) {
                $this->radius = $r;
                return 2 * self::PI * $this->radius;
            }
        }

     $C = new Circle();
    //Argument was passed directly to the method
    echo ("Circumference of Circle: ".$C->calculate(7));
 ?>
  • 写回答

1条回答 默认 最新

  • doushi1957 2017-07-22 22:08
    关注

    Adding a constructor method is optional. The documentation states:

    PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object.

    Note however that your second implementation is not ideal:

    • the calculate method has a side-effect: it sets the radius member. This is not best practice: if a method's main purpose is to return something, then it should not mutate the object.

    • the calculate method requires you to provide the radius on every call. This is not really what you want when the object is supposed to know its radius.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?