Search

Laravel Miscellaneous Helper Function: with

November 21, 2016 —John Koster

with($object)

The with function will simply return the supplied $object. This function can be used to invoke methods on new class instances that are passed as function arguments:

1<?php
2 
3class ExampleClass {
4 
5 public function someMethod()
6 {
7 return 'some value';
8 }
9 
10 // Other methods.
11 
12}
13 
14$value = with(new ExampleClass)->someMethod();

In the above example, $value would be contain the value some value.

#Alternative to The with Function

The same effect provided by the with function can be accomplished using vanilla PHP. The technique is to wrap object instantiation within a pair of parenthesis (( and )):

1<?php
2 
3$value = (new ExampleClass)->someMethod();

Again, the value of $value would be some value. Both vanilla PHP method and the with method are perfectly capable. However, the with function may help to improve readability and clarify intent.