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);
3

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.