简体   繁体   English

在 PHP 函数中引用类变量作为默认参数

[英]Referring to class variables as default parameters in PHP function

I would like to have a function in my class that has a default parameter so that one can omit the argument if required.我想在我的类中有一个函数,它有一个默认参数,以便在需要时可以省略该参数。 I want the default to be a variable stored in my class;我希望默认值是存储在我的类中的变量;

Hi why is this showing error messages in Aptana?嗨,为什么这会在 Aptana 中显示错误消息?

class property{
    private $id;
    function load_data($id = $this->id){
        //...blah blah blah
    }
}

Should I instead use我应该改用

class property{
    static $id;
    function load_data($id = self::id){
        //...blah blah blah
    }
}

? ?

Thanks for the help谢谢您的帮助

I'm pretty sure you can't do what you're looking for.我很确定你不能做你正在寻找的东西。 Instead you should simply check to see if the argument has a value, and if it doesn't, assign the default value which is the object property.相反,您应该简单地检查参数是否有值,如果没有,则分配默认值,即对象属性。

class property{
    private $id;
    function load_data($id = null){
        $id = (is_null($id)) ? $this->id : $id;
    }
}

You could do this:你可以这样做:

class property
{
    private $id;

    function load_data($id = null){

        if (is_null($id)) {
            $id = $this->id;
        }

        //...blah blah blah
    }
}

I know its an old question but I came up on it searching for the same kind of thing and the answer is yes you can do it, as long as you define it as a constant:我知道这是一个老问题,但我想出了它来寻找同样的事情,答案是肯定的,你可以做到,只要你把它定义为一个常量:

class property{
    const $id;
    function load_data($id = self::id){
        //...blah blah blah
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM