【问题标题】:How to check if a function has a value [duplicate]如何检查函数是否有值[重复]
【发布时间】:2014-07-03 03:28:38
【问题描述】:

我不确定标题是否正确,我的问题是我里面有一个类和函数,我想检查函数的值是否设置,如果没有设置其他值

class some_class
{
    private $width;

    function width( $value )
    {
        // Set another default value if this is not set
        $this->width = $value;
    }
}

$v = new some_class();


// Set the value here but if I choose to leave this out I want a default value
$v->width( 150 );

【问题讨论】:

  • 如果您使用的是 setter 方法,请按原样调用它:setWidth

标签: php oop


【解决方案1】:

这可能就是你要找的东西

class some_class
{
    function width($width = 100)
    {
        echo $width;
    }
}

$sc = new some_class();

$sc->width();
// Outputs 100

$sc->width(150);
// Outputs 150

【讨论】:

  • 您是否有理由发布已经发布的答案,同时也完全改变了 OP 使用的示例?
  • 不知何故,我需要 3 多分钟来创建答案。在打字时,我不会一直在寻找其他答案。
【解决方案2】:

你可以这样做:

class SomeClass
{
    private $width;

    function setWidth($value = 100)
    {
        $this->width = $value;
    }
}

$object = new SomeClass();
$object->setWidth();
echo '<pre>';
print_r($object);

如果为空会变成这样:

SomeClass Object
(
    [width:SomeClass:private] => 100
)

或者类似的东西:

class SomeClass
{
    private $width;

    function setWidth()
    {
        $this->width = (func_num_args() > 0) ? func_get_arg(0) : 100;
    }
}

$object = new SomeClass();
$object->setWidth();
echo '<pre>';
print_r($object); // same output

【讨论】:

    【解决方案3】:

    试试这个

    class some_class
    {
        private $width;
        function width( $value=500 )  //Give default value here
        {
            $this->width = $value; 
        }
    }
    

    检查Manual 的默认值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-30
      • 2013-11-14
      • 2011-11-14
      • 2019-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多