-1

I have a class.php with a construct

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

In other file when i want call this in this ways works:

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

but i need call something :

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


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

All this appears like undefined. I saw this isnt the correct way, but how i can do? Thanks very much!

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Francisco
  • 11
  • 3
  • Did you set the values of `$name1, $color1` and `$name2, $color2` Before using them on a call to instantiate the new object – RiggsFolly May 17 '20 at 14:30
  • Cannot Reproduce: Unless you are doing things in the order you show in the question, which is obviously the wrong order – RiggsFolly May 17 '20 at 14:41

1 Answers1

0

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

Change your code to

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

Kunal Raut
  • 2,495
  • 2
  • 9
  • 25