I have come across this line in the eloquent ORM library:
return with(new static)->newQuery();
I've never seen "with" used before, and cannot find it in the PHP documentation. I'm guessing "with" is a stop-word in most searches, so I am not even getting close.
Never having encountered "with" in many years of programming PHP, I feel like I'm missing out. What does it do? I did come across one passing comment regarding the ORM, that mentioned "with" is no longer needed in PHP-5.4, but that was as much as was said. If that is accurate, it would be good to know what the PHP-5.4 equivalent is.
Update: Details supporting the answer:-
I found this helper function in Laravel's Immuminate/Support/helpers.php helper script:
if ( ! function_exists('with'))
{
/**
* Return the given object. Useful for chaining.
*
* @param mixed $object
* @return mixed
*/
function with($object)
{
return $object;
}
}
as mentioned in a few of the answers. That global-scope function allows an object to be created and methods run in t, in one statement. It is (somehow) registered in the composer autoload_files.php script when Laravel is installed, so it gets loaded on every page, even though it contains no classes.
Thanks all. It pays not to assume that everything must be a namespaced class in modern frameworks.
It makes PHP suppress any error messages (notice, warning, fatal, etc) generated by the associated expression. It works just like a unary operator, for example, it has a precedence and associativity.
PHP Operator is a symbol i.e used to perform operations on operands. In simple words, operators are used to perform operations on variables or values. For example: $num=10+20;//+ is the operator and 10,20 are operands.
$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.
It's a function that will look something like this:
function with($obj) {
return $obj;
}
It's shorter version and more readable version for new ExampleObj()->newQuery()
.
with
function is not build in PHP. It's workaround for older versions than PHP 5.4. As @Rocket Hazmat pointed in PHP 5.4+ you can do just new ExampleObj()->newQuery()
so with
function here allow you to keep readable backward compatibility.
The with
function is a helper provided by Laravel as documented here. The best documentation is the code and as you can see, it simply returns the object. In 5.4 / 5.4 you are better off just surrounding the expression in parens to avoid the overhead of an unnecessary function call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With