0

In python you can set specific parameters when you call a function or create an object. Can you do something similar in PHP?

For example

class Ingredient {
    private $calories;
    private $weight;

    public function __construct($calories=100, $weight=2) {
        $this->calories = $calories;
        $this->weight = $weight;
    }
}

$flour = new Ingredient(weight=4);
$sugar = new Ingredient(calories=143);

I know an alternative is to have an empty constructor and then set each attribute individually, but that looks messy and is long.

Or in functions

function transaction_cost($cost=30, $fee=12, $shipping=3) {
   return $cost + $fee + $shipping;
}

$apple_cost = transaction_cost(cost=12);
$banana_cost = transaction_cost(fee=43);
James
  • 299
  • 1
  • 12
  • [Named arguments will be a thing in PHP 8.](https://wiki.php.net/rfc/named_params) – Jeto Jul 26 '20 at 09:18
  • In the meantime, you could use value objects / [data transfer objects](https://github.com/spatie/data-transfer-object). – Jeto Jul 26 '20 at 09:22
  • Does this answer your question? [PHP Default Function Parameter values, how to 'pass default value' for 'not last' parameters?](https://stackoverflow.com/questions/10597114/php-default-function-parameter-values-how-to-pass-default-value-for-not-last) – Leo Jul 26 '20 at 12:02

0 Answers0