【问题标题】:A question on an example in PHP 5 in Practice关于 PHP 5 in Practice 中示例的问题
【发布时间】:2009-06-12 22:26:55
【问题描述】:

你好,我不明白为什么php书的作者在公共函数__construct($disks = 1)中使用了$disks = 1?

我尝试仅用 $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>';
?>

【问题讨论】:

    标签: php class object


    【解决方案1】:

    他正在为 $disks 设置一个默认值,所以如果你在没有参数的情况下实例化该类,$disks 将被设置为 1。

    例子:

    class Foo {
        function __construct($var = 'hello') {
            print $var;
        }
    }
    
    f = new Foo('hi'); // prints 'hi'
    f = new Foo(); // prints 'hello'
    

    【讨论】:

    【解决方案2】:

    这称为默认值。如果 $disks 在调用时没有设置任何值,它将自动采用默认值,在本例中为 1。

    但是,如果你把方法改成这样:

    __construct($disks = 1, $somethingElse)
    

    这行不通。如果您提供默认值,则以下值也必须具有默认值。更有趣的是,如果你这样做:

    __construct($somethingElse, $disks = 1)
    

    它会起作用的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-17
      • 2022-12-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2020-08-03
      • 2022-10-01
      相关资源
      最近更新 更多