0

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 );
Gottlieb Notschnabel
  • 9,408
  • 18
  • 74
  • 116

3 Answers3

0

Try this

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

Check Manual for default value.

Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
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
Gottlieb Notschnabel
  • 9,408
  • 18
  • 74
  • 116
  • Is there a reason you've posted an answer already posted, while also completely changing the example the OP was using? – jeremy Jul 03 '14 at 03:37
  • There is somehow a reason, I needed more than 3 minutes to create the answer. And while typing, I'm not constantly looking for other answers flying in. – Gottlieb Notschnabel Jul 03 '14 at 03:40
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