调用构造

我有一个带有构造的class.php

<?php
class Fruit {
  public $name;
  public $color;

  function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }
  function get_name() {
    return $this->name;
  }
  function get_color() {
    return $this->color;
  }
}

在其他文件中我想打电话给我时 以这种方式工作:

$apple1 = new Fruit("Apple", "red");
$apple2 = new Fruit("Apple", "yellow");

但我需要打电话:

$apple1 = new Fruit($name1, $color1);
$apple2 = new Fruit($name2, $color2);


$name1='Apple';
$color1= get_user_meta($user_id, 'color', true);
$name2='Apple';
$color2='yellow';

所有这些看起来像未定义。我看到这不是正确的方法,但是我该怎么办? 非常感谢!

评论
  • 孩,他爹
    孩,他爹 回复

    You can call a __construct by variables but for that you must specify them before you instantiate new object.

    将您的代码更改为

    $name1='Apple';
    $name2='Apple';
    $color2='yellow';
    $apple1 = new Fruit($name1, $color1);
    $apple2 = new Fruit($name2, $color2);
    $color1= get_user_meta($user_id, 'color', true);