This question already has an answer here:
这个问题在这里已有答案:
- How do you create optional arguments in php? 6 answers
你如何在PHP中创建可选参数? 6个答案
I am not sure if the title is correct, my problem is that I have a class and functions inside it, I would like to check if the value for the function is set and if not set other value
我不确定标题是否正确,我的问题是我有一个类和函数,我想检查函数的值是否设置,如果没有设置其他值
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 );
3 个解决方案
#1
0
This might be what you're looking for
这可能是你正在寻找的
class some_class
{
function width($width = 100)
{
echo $width;
}
}
$sc = new some_class();
$sc->width();
// Outputs 100
$sc->width(150);
// Outputs 150
#2
0
You can do something like this:
你可以这样做:
class SomeClass
{
private $width;
function setWidth($value = 100)
{
$this->width = $value;
}
}
$object = new SomeClass();
$object->setWidth();
echo '<pre>';
print_r($object);
Will result into like this if empty:
如果为空则会产生这样的结果:
SomeClass Object
(
[width:SomeClass:private] => 100
)
or something like this too:
或类似的东西:
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
0
Try this
class some_class
{
private $width;
function width( $value=500 ) //Give default value here
{
$this->width = $value;
}
}
Check Manual for default value.
检查手动的默认值。
#1
0
This might be what you're looking for
这可能是你正在寻找的
class some_class
{
function width($width = 100)
{
echo $width;
}
}
$sc = new some_class();
$sc->width();
// Outputs 100
$sc->width(150);
// Outputs 150
#2
0
You can do something like this:
你可以这样做:
class SomeClass
{
private $width;
function setWidth($value = 100)
{
$this->width = $value;
}
}
$object = new SomeClass();
$object->setWidth();
echo '<pre>';
print_r($object);
Will result into like this if empty:
如果为空则会产生这样的结果:
SomeClass Object
(
[width:SomeClass:private] => 100
)
or something like this too:
或类似的东西:
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
0
Try this
class some_class
{
private $width;
function width( $value=500 ) //Give default value here
{
$this->width = $value;
}
}
Check Manual for default value.
检查手动的默认值。