Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

amir5's avatar
Level 7

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	
	},
};
0 likes
6 replies
Sinnbeck's avatar

Use a method. It will much clearer tell you in the future what it does..

match('test') {
	'test' => $this->doTestStuff(),
};
1 like
tykus's avatar
tykus
Best Answer
Level 104

@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!

3 likes
amir5's avatar
Level 7

@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...

Sinnbeck's avatar

You can also use laravel's value() function if it returns something

$foo = match('foo') {
    'foo' => (function () {
        return 'foo';
    }),
    default => null,
};
dd(value($foo));

2 likes
EveAT's avatar

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	
	})(),
};
1 like

Please or to participate in this conversation.