tags:

views:

74

answers:

2

HI, I don't understand why the author of a php book used $disks = 1 in a public function __construct($disks = 1)?

I tried to replace $disks = 1 with $disks only, it also worked. Why would author doing that?

<?php
// Define our class for Compact disks
class cd {
    // Declare variables (properties)
    public $artist;
    public $title;
    protected $tracks;
    private $disk_id;

    // Declare the constructor
    public function __construct() {
        // Generate a random disk_id
        $this->disk_id = sha1('cd' . time() . rand());
    }

    // Create a method to return the disk_id, it can't be accessed directly
    // since it is declared as private.
    public function get_disk_id() {
        return $this->disk_id;
    }
}

// Now extend this and add multi-disk support
class cd_album extends cd {
    // Add a count for the number of disks:
    protected $num_disks;

    // A constructor that allows for the number of disks to be provided
    public function __construct($disks = 1) {
        $this->num_disks = $disks;

        // Now force the parent's constructor to still run as well
        //  to create the disk id
        parent::__construct();
    }

    // Create a function that returns a true or false for whether this
    //  is a multicd set or not?
    public function is_multi_cd() {
        return ($this->num_disks > 1) ? true : false;
    }
}

// Instantiate an object of class 'cd_album'.  Make it a 3 disk set.
$mydisk = new cd_album(3);

// Now use the provided function to retrieve, and display, the id
echo '<p>The compact disk ID is: ', $mydisk->get_disk_id(), '</p>';

// Use the provided function to check if this is a a multi-cd set.
echo '<p>Is this a multi cd? ', ($mydisk->is_multi_cd()) ? 'Yes' : 'No', '</p>';
?>
+13  A: 

He is setting a default value for $disks, so if you instantiate the class without an argument, $disks will be set to 1.

Example:

class Foo {
    function __construct($var = 'hello') {
        print $var;
    }
}

f = new Foo('hi'); // prints 'hi'
f = new Foo(); // prints 'hello'
cloudhead
Nothing more to say, except a reference: http://docs.php.net/manual/en/functions.arguments.php
Boris Guéry
+2  A: 

That's called a default. If no value happens to be set for $disks when its called, it will automatically assume the default, in this case 1.

However, if you change the method to this:

__construct($disks = 1, $somethingElse)

It wouldn't work. If you supply a default, then values following must also have a default. Even more interesting, if you did this:

__construct($somethingElse, $disks = 1)

It would work.

Wade