繁体   English   中英

PHP:检查是 null 作为参数传递或分配为默认值

[英]PHP: Check is null was passed as a parameter or assigned as the default

我正在尝试编写我的 object 成员,以便可以使用以下格式访问它们:

$object->member() // Returns current value of member
$object->member($new_value) // Sets value of member to $new_value

这是我的实现示例:

class Automobile
{
    private $color;
    private $make;
    private $model;

    public function __construct($inColor, $inMake, $inModel) {
        $this->color($inColor);
        $this->make($inMake);
        $this->model($inModel);
    }

    private function gset($p, $v) {
        if ($v) {
            $this->{$p} = $v;
            return $this;
        } else {
            return $this->{$p};
        }
    }

    public function color($v = null) {
        return $this->gset(__FUNCTION__, $v);
    }
    public function make($v = null) {
        return $this->gset(__FUNCTION__, $v);
    }
    public function model($v = null) {
        return $this->gset(__FUNCTION__, $v);
    }
}

我正在寻找的效果是:

$car = new Automobile('Red', 'Honda', 'Civic');

var_dump($car->color()); // Returns Red
$car->color('Blue'); // Sets color to Blue
var_dump($car->color()); // Returns Blue

Everything works great as is, HOWEVER I'd like to also be able to literally pass null to the function so it will insert null as the value, but since the default of the parameter is null also it will only return the current value:

$car->color(null); // Would like to insert null as car color, but this is obviously equivalent to $car->color()
var_dump($car->color()); // Returns Blue

无论如何要知道一个值是传递的实际参数的结果还是使用默认值的结果? 我认为我的第一个测试机会是在 function 本身内部,到那时它已经设置好了。

关于如何实现我正在寻找的任何其他想法?

我意识到我可以编写一个单独的 function 到null一个特定的成员,例如$car->null_color() ,但目前我正试图以某种方式将它压缩成相同的$object->member()格式。

使用func_num_args()确定是否有任何 arguments 通过。

function color($c = null) {
    if(func_num_args() == 1) {
        $this->color = $c;
    }
    return $this->color;
}

这是你要找的吗?

public function color($v = null) {

    //If nothing or NULL is sent to this function 
    //return current color
    if ($v === null) return $this->color; 

    //Set color
    $this->color = $v;
}

暂无
暂无

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

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