2009-06-12 42 views
1

嗨,我不明白爲什麼php書的作者在公共函數__construct($ disks = 1)中使用$ disks = 1?關於PHP 5實踐中的一個例子的問題

我試圖只用$ disks替換$ disks = 1,它也起作用。爲什麼作者會這樣做?

<?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

他爲$磁盤設置默認值,所以如果你實例化類不帶參數,$磁盤將被設置爲1

例子:

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

f = new Foo('hi'); // prints 'hi' 
f = new Foo(); // prints 'hello' 
+0

沒什麼可說的,除了一個參考:http://docs.php.net/manual/en/functions.arguments.php – 2009-06-12 22:40:35

2

這就是所謂的默認。如果沒有值發生了$磁盤設置其調用時,它會自動採用默認設置,在這種情況下,1

但是,如果你改變的方法是:

__construct($disks = 1, $somethingElse) 

它止跌」工作。如果您提供默認值,則以下值還必須具有默認值。更有趣的是,如果你這樣做:

__construct($somethingElse, $disks = 1) 

它會工作。