2014-07-03 32 views
0

我不確定標題是否正確,我的問題是我有一個類和它的函數,我想檢查函數的值是否設置,如果不設置其他值如何檢查一個函數是否有值

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); 
+1

如果您使用setter方法,請按原樣調用它:'setWidth'。 – jeremy

回答

0

試試這個

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

檢查Manual爲默認值。

0

這可能是你在找什麼

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

$sc = new some_class(); 

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

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

您是否有理由發佈已發佈的答案,同時也完全改變了OP使用的示例? – jeremy

+0

有一個原因,我需要超過3分鐘才能創建答案。而在打字時,我並不是經常在尋找其他答案。 –

0

你可以做這樣的事情:

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 
相關問題