【问题标题】:Optional argument in a class method with $this in PHPPHP 中带有 $this 的类方法中的可选参数
【发布时间】:2018-05-16 19:20:14
【问题描述】:

我有一个与此相关的问题:

How to create constructor with optional parameters?

很明显,我们可以像这样制作可选参数:

function myFunction($param='hello')

但我想在类的方法中使用$this->something 而不是'hello',它看起来像这样:

public function myFunction($param=$this->property)

但我得到一个:

Parse error: syntax error, unexpected '$this'

能买到吗?

【问题讨论】:

  • 将其设置为 null,如果为 null,则将其设置为方法中的属性。

标签: php class methods parameters


【解决方案1】:

你需要设置为null然后检查

 class example {
 private $something = "something";
 public function myFunction($a = null) 
 {
    if($a === null) 
       $a = $this->something; 
     // more code goes here
    return $a; 
  }
 }
 $test = new example();
 print $test->myFunction();
 // prints "something"
 print $test->myFunction("hello");
 // prints "hello"

【讨论】:

    【解决方案2】:

    你可以这样做

    $Obj = new myclass();
    class myclass{
    
        var $data = 'tested';
        function __construct(){
            $this->testFunction();
        }
    
        public function testFunction($param = null){
            if( $param == '' || $param == null){
                $param = $this->data;
            }
            echo $param;
        }
    }
    

    【讨论】:

    • 我认为 if($param=== null) 会比 if($param=='' OR $param ==null) 更好,因为 '' 可能是我的有效值案例,无论如何,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2013-08-11
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多