How to write multiline statements for match
I'm using php's match, but some cases require more lines. I also tried passing closures but match won't evaluate them.
match('test') {
'test' => function() {
// some lines
dd(3); // wont get executed
},
};
Use a method. It will much clearer tell you in the future what it does..
match('test') {
'test' => $this->doTestStuff(),
};
@amir5 you can execute your Closure, like this
match('test') {
'test' => (function() {
// some lines
dd(3); // wont get executed
})(),
};
But it gets messy.... as @sinnbeck says, use a separate function!
@tykus Was just testing if this was possible :D Beat me to it
@tykus Oh, before I wanted to post this question, I'd tried executing closure like this but got syntax error:
match('test') {
'test' => function() {
// some lines
dd(3); // wont get executed
}(),
};
I should've wrapped closure in parentheses...
You can also use laravel's value() function if it returns something
$foo = match('foo') {
'foo' => (function () {
return 'foo';
}),
default => null,
};
dd(value($foo));
In your exemple the match return a closure, so you need to execute it.
$result = match('test') {
'test' => function() {
// some lines
dd(3); // wont get executed
},
};
$result();
To execute it right away, you can use an immediately invoked closure:
match('test') {
'test' => (function() {
// some lines
dd(3); // will be executed
})(),
};
Please or to participate in this conversation.