8

異なる数のパラメータを受け入れることができるphpコンストラクタを実装する方法は?

お気に入り

class Person {
    function __construct() { 
        // some fancy implementation
    } 
} 

$a = new Person('John');
$b = new Person('Jane', 'Doe');
$c = new Person('John', 'Doe', '25');

これをphpで実装する最良の方法は何ですか?

ありがとう、ミロ

4

2 に答える 2

11

1つの解決策は、デフォルトを使用することです。

public function __construct($name, $lastname = null, $age = 25) {
    $this->name = $name;
    if ($lastname !== null) {
        $this->lastname = $lastname;
    }
    if ($age !== null) {
        $this->age = $age;
    }
}

2つ目は、配列、連想配列、またはオブジェクトを受け入れることです(連想配列の例)。

public function __construct($params = array()) {
    foreach ($params as $key => $value) {
        $this->{$key} = $value;
    }
}

しかし、2番目のケースでは、次のように渡す必要があります。

$x = new Person(array('name' => 'John'));

3番目のオプションはtanduによって指摘されています:

コンストラクター引数は、他の関数の引数と同じように機能します。デフォルトのphp.net/manual/en/…を指定するか、を使用しますfunc_get_args()

編集: tandu(現在:Explosion Pills)による元の回答から取得できたものをここに貼り付けました。

于 2011-05-13T01:11:40.347 に答える
3

更新された回答:

echo '<pre>';

// option 1 - combination of both tadeck's and my previous answer

class foo {
    function __construct() {
        $arg_names = array('firstname', 'lastname', 'age');
        $arg_list = func_get_args();
        for ($i = 0; $i < func_num_args(); $i++) {
            $this->{$arg_names[$i]} = $arg_list[$i];
        }
    }
}

$foo = new foo('John', 'Doe', 25);

print_r($foo);

// option 2 - by default, PHP lets you set arbitrary properties in objects, even
// if their classes don't have that property defined - negating the need for __set()

// you will need to set properties one by one however, rather than passing them as
// parameters

class bar {
}

$bar = new bar();
$bar->firstname = 'John';
$bar->lastname = 'Doe';
$bar->age = 25;

print_r($bar);

結果:

foo Object
(
    [firstname] => John
    [lastname] => Doe
    [age] => 25
)
bar Object
(
    [firstname] => John
    [lastname] => Doe
    [age] => 25
)

前の回答:

<?php

class Person {
    function __construct() {
        $arg_list = func_get_args();
        echo '<p>';
        for ($i = 0; $i < func_num_args(); $i++) {
            echo 'Argument '.$i.' is: '.$arg_list[$i].'<br />', "\n";
        }
    }
}

$a = new Person('John');
$b = new Person('Jane', 'Doe');
$c = new Person('John', 'Doe', '25');

?>

結果:

Argument 0 is: John

Argument 0 is: Jane
Argument 1 is: Doe

Argument 0 is: John
Argument 1 is: Doe
Argument 2 is: 25
于 2011-05-13T01:42:26.767 に答える