Can I set up a default method argument with class property in PHP?

前端 未结 4 1391
离开以前
离开以前 2020-12-18 21:19

I\'m using PHP 5.2.6. I want to have a default value for an argument in a method, but it seems I\'m getting a bit too clever.

The class property blnOverwrite

4条回答
  •  渐次进展
    2020-12-18 22:03

    You absolutely can do this. Best of both worlds: initialize your default property AND your method's default argument with a class constant.

    class Object {
    
        const DEFAULT_BLNOVERWRITE = TRUE;
    
        protected $blnOverwrite = self::DEFAULT_BLNOVERWRITE;
    
        public function place($path, $overwrite = self::DEFAULT_BLNOVERWRITE) {
            var_dump($overwrite);
        }
    }
    
    $Object = new Object();
    $Object->place('/'); //bool(true)
    

提交回复
热议问题