Calling a function
Class::name(args) calls a static method. $object->name(args) calls a method on an object. You
can pass an argument by position, or by name: greet(name: "Bob").
Calls
A call runs a method and returns the method's result.
You write the class or the object, the name of the method, and the arguments in brackets. You can call a method on the result of a call directly. Arguments go in the order of the parameters. You can also write them by name, in any order. A name also lets you leave out a parameter in the middle that has a default. A variadic parameter, written ...$rest, takes any number of arguments. ...$list at the call passes each value of an array as an argument. An inout parameter writes its new value back to the variable you passed. You write inout at the call as well.
Good to know: you call a callable through the variable, the array element or the property that contains it. Its arguments are checked when the program runs.
The examples below take these in turn: calling and chaining, naming the arguments you pass, and pricing an order with the handler the customer chose. The last one shows each way to write a call in one program.
Calling a method and chaining the result
<?nvs// Shows how a call is written and how calls chain. A static method is called// on the class and an instance method on an object. You can call a method on// the object that a call returns directly.
class Greeting{ public function constructor(private string $word) {}
// Builds a greeting so the caller does not have to know the word for each // language. public static function in(string $language): Greeting { return new Greeting(match ($language) { 'de' => 'Hallo', 'fr' => 'Bonjour', default => 'Hello', }); }
public function to(string $name): string { return $this->word . ', ' . $name . '!'; }}
// The static call returns an object, and `->to` is called on it.// This prints: Bonjour, Ada!echo Greeting::in('fr')->to('Ada'), "\n";
// `new` chains in the same place, with no brackets around it.// This prints: Hello, Bob!echo new Greeting('Hello')->to('Bob'), "\n";
// When you need the object more than once, store it in a variable first.// This prints: Hallo, Cem! Hallo, Dara!Greeting $german = Greeting::in('de');echo $german->to('Cem'), ' ', $german->to('Dara'), "\n";Bonjour, Ada!Hello, Bob!Hallo, Cem! Hallo, Dara!Naming the arguments you pass
<?nvs// Shows the ways to write the arguments of a call: by position, by name in// any order, and as an array passed to a method that takes any number of// arguments.
class Ticket{ // The last two parameters have a default, so a caller may write one // argument or all three. public static function price(int $seats, int $each = 20, int $booking = 3): int { return $seats * $each + $booking; }
// `...$prices` collects everything left over into one array. public static function cheapest(int ...$prices): int { int $best = 0;
foreach ($prices as int $price) { if ($best == 0 || $price < $best) { $best = $price; } }
return $best; }}
// By position: the first argument is for the first parameter, and so on.// This prints 43.echo Ticket::price(2, 20, 3), "\n";
// By name, in any order. The parameter `each` in the middle is left out, so// it has its default of 20. This prints 26.echo Ticket::price(booking: 6, seats: 1), "\n";
// Any number of arguments. This prints 26.echo Ticket::cheapest(43, 26, 33), "\n";
// `...` passes each value of an array as one argument. This prints 26.array<int> $offers = [43, 26, 33];echo Ticket::cheapest(...$offers), "\n";43262626Pricing an order at checkout
<?nvs// Shows calls doing the work of a checkout. The basket totals itself, and the// shipping charge comes from the handler the customer chose. The running total// is added up through a parameter that is written back. All amounts are in// cents.
class Basket{ public function constructor(private array<int> $lines) {}
public function goods(): int { int $total = 0;
foreach ($this->lines as int $line) { $total = $total + $line; }
return $total; }}
class Checkout{ // `inout` writes the new value back into the caller's own variable, so // every step adds to the same total without assigning the result. public static function add(inout int $total, int $amount): void { $total = $total + $amount; }
// Most callers take the standard rate, so it has a default and is named // at the call that needs a different one. public static function tax(int $amount, int $rate = 20): int { return Core\Math::quotient($amount * $rate, 100); }}
// One handler per shipping method, chosen by the name that arrives with the// order. Each one is given the value of the goods and returns the charge.array<callable> $shipping = [ 'standard' => fn(int $goods): int => $goods >= 5000 ? 0 : 495, 'express' => fn(int $goods): int => 1295, 'collect' => fn(int $goods): int => 0,];
Basket $basket = new Basket([1299, 450, 2600]);string $method = 'standard';
int $total = 0;Checkout::add(inout $total, $basket->goods());Checkout::add(inout $total, $shipping[$method]($basket->goods()) as int);Checkout::add(inout $total, Checkout::tax($basket->goods()));
// This prints: goods 4349 shipping standard total 5713echo 'goods ', $basket->goods(), ' shipping ', $method, ' total ', $total, "\n";
// The argument `rate: 5` sets a reduced tax rate. This prints: reduced total 5061int $reduced = 0;Checkout::add(inout $reduced, $basket->goods());Checkout::add(inout $reduced, $shipping[$method]($basket->goods()) as int);Checkout::add(inout $reduced, Checkout::tax($basket->goods(), rate: 5));echo 'reduced total ', $reduced, "\n";goods 4349 shipping standard total 5713reduced total 5061Every way to write a call
<?nvs// Shows each way to write a call: chained, named, variadic, `inout` and through a `callable`.
class Greeter{ public function constructor(private string $greeting) {}
public function greet(string $name, string $mark = '!'): string { return $this->greeting . ', ' . $name . $mark; }
public static function make(): Greeter { return new Greeter('Hi'); }
public static function sum(int ...$xs): int { int $t = 0; foreach ($xs as int $x) { $t += $x; } return $t; }
public static function twice(inout int $n): void { $n = $n * 2; }}
// A chained call, and named arguments in any order. This prints: Hi, Ada! Yo, Bob?echo Greeter::make()->greet('Ada'), ' ', new Greeter('Yo')->greet(mark: '?', name: 'Bob'), "\n";
// `sum` takes any number of arguments, also none. `twice` changes `$n` to 8.// This prints: 6 9 0 8array<int> $xs = [4, 5];int $n = 4;Greeter::twice(inout $n);echo Greeter::sum(1, 2, 3), ' ', Greeter::sum(...$xs), ' ', Greeter::sum(), ' ', $n, "\n";
// A `callable` in a variable, in an array element, and an anonymous function called directly.// The extra argument `99` is ignored. This prints: 2 2 8 40callable $f = fn(int $x): int => $x + 1;array<callable> $ops = ['dbl' => fn(int $x): int => $x * 2];echo $f(1), ' ', $f(1, 99), ' ', $ops['dbl'](4), ' ', (fn(int $x): int => $x * 10)(4), "\n";Hi, Ada! Yo, Bob?6 9 0 82 2 8 40Spreading an array into fixed parameters
<?nvs// Shows that `...` works only for a variadic parameter. Here `add` has two fixed parameters.// proof: compile-error
class Pair{ public static function add(int $a, int $b): int { return $a + $b; }}
array<int> $xs = [1, 2];echo Pair::add(...$xs), "\n";error[E0489]: a `...` argument has no variadic parameter to spread into --> 05-spreading-an-array-into-fixed-parameters.nvs:14:16 |14 | echo Pair::add(...$xs), "\n"; | ^^^^^^ this call's target declares no `...` parameter = help: a `...` only ever supplies a `...$rest` tail, because how many entries an array holds is a run-time fact and a fixed parameter list has to be counted — write the arguments out
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
The arguments run in the order they are written, also when they are named. In A::f(b: A::v(2), a: A::v(5)), A::v(2) runs first.
A static method may also be called on an object: $p->s() calls the static method s. An instance method called on the class, such as P::i(), is the error E0778. A method the class does not have is the error E0405. On a nullable object, such as a ?P, $p->hi() is the error E0459. Use $p?->hi(), which gives null when $p is null.
...$list only fills a variadic parameter. Before a method with only fixed parameters, it is the error E0489. Arguments may come before it, and several ... arguments may follow each other: A::f(3, ...$xs) and A::f(...$xs, ...$xs) both work. The type of the array must match the variadic parameter, so an array<string> for int ...$a is the error E0401. The keys of the array are kept: ["x" => 1, "y" => 2] arrives with the keys "x" and "y".
A call through a callable gives mixed. int $r = $f(1) is the error E0401, so write $f(1) as int. The arguments are checked when the call runs. An argument of the wrong type throws a LogicError: `argument 1 to a callable must be of type int, string given. Too few arguments throw a LogicError` too, and extra arguments are ignored.
A callable in a property needs brackets around it: ($this->cb)(1). Without them, $this->cb(1) calls a method named cb, and is the error E0405 when the class has none.
A call that returns void has no value. At an int variable it is the error E0401, and after echo it is the error E0707.
The page Parameters and inout shows how a method declares what a call passes.
Do and don’t
Section titled “Do and don’t”- Do use a named argument when the meaning of a value is not clear:
resize(width: 80). - Do convert the result of a callable with
asbefore you use it. - Don’t call a
callablewith too few arguments. The call throws an error. - Don’t write
$this->callback(1)for a property. This syntax calls a method namedcallback. If there is no such method, it does not compile.
