【问题标题】:PHP constructor with a parameter带参数的 PHP 构造函数
【发布时间】:2012-02-19 04:56:13
【问题描述】:

我需要一个可以执行以下操作的函数:

$arr = array(); // This is the array where I'm storing data

$f = new MyRecord(); // I have __constructor in class Field() that sets some default values
$f->{'fid'} = 1;
$f->{'fvalue-string'} = $_POST['data'];
$arr[] = $f;

$f = new Field();
$f->{'fid'} = 2;
$f->{'fvalue-int'} = $_POST['data2'];
$arr[] = $f;

当我写这样的东西时:

$f = new Field(1, 'fvalue-string', $_POST['data-string'], $arr);
$f = new Field(2, 'fvalue-int', $_POST['data-integer'], $arr);

// Description of parameters that I want to use:
// 1 - always integer, unique (fid property of MyRecord class)
// 'fvalue-int' - name of field/property in MyRecord class where the next parameter will go
// 3. Data for field specified in the previous parameter
// 4. Array where the class should go

我不知道如何在 PHP 中制作参数化构造函数。

现在我使用这样的构造函数:

class MyRecord
{
    function __construct() {
        $default = new stdClass();
        $default->{'fvalue-string'} = '';
        $default->{'fvalue-int'} = 0;
        $default->{'fvalue-float'} = 0;
        $default->{'fvalue-image'} = ' ';
        $default->{'fvalue-datetime'} = 0;
        $default->{'fvalue-boolean'} = false;

        $this = $default;
    }
}

【问题讨论】:

    标签: php constructor


    【解决方案1】:

    阅读所有Constructors and Destructors

    构造函数可以像 PHP 中的任何其他函数或方法一样接受参数:

    class MyClass {
    
      public $param;
    
      public function __construct($param) {
        $this->param = $param;
      }
    }
    
    $myClass = new MyClass('foobar');
    echo $myClass->param; // foobar
    

    您如何使用构造函数的示例现在甚至无法编译,因为您无法重新分配 $this

    此外,您不需要每次访问或设置属性时都使用大括号。 $object->property 工作得很好。你只需要在特殊情况下使用花括号,比如如果你需要评估一个方法$object->{$foo->bar()} = 'test';

    【讨论】:

    • 你是对的。它不起作用。我如何用默认值初始化属性 {'fvalue-string'}?
    • 我昨天尝试了带有多个参数的构造函数,但它们没有工作,我做错了,因为我出错了。我在构造函数中看到了很多 __construct(array) 和“解包”数组的例子,所以我认为我不能在 PHP 中创建带有很多参数的构造函数。我错了。谢谢。
    • 为什么要公开 $param ?你不能把return $param放在构造函数中并像echo new MyClass('foobar')一样调用类吗?
    【解决方案2】:

    如果您想将数组作为参数传递并“自动”填充您的属性:

    class MyRecord {
        function __construct($parameters = array()) {
            foreach($parameters as $key => $value) {
                $this->$key = $value;
            }
        }
    }
    

    请注意,构造函数用于创建和初始化对象,因此可以使用$this 来使用/修改您正在构造的对象。

    【讨论】:

      猜你喜欢
      • 2011-10-08
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      • 2021-10-25
      • 2013-11-07
      • 2015-01-13
      • 1970-01-01
      相关资源
      最近更新 更多