- Curly brace syntax in PHP?
- 3 Answers 3
- Unexpected closing curly brace > error
- “Array and string offset access syntax with curly braces is deprecated” – How To Fix It?
- How does the error “Array and string offset access syntax with curly braces is deprecated” occur?
- How “Array and string offset access syntax with curly braces is deprecated” can be solved?
- Solution 1: Access Array in PHP 7. X
- Curly braces Fatal Errors after PHP 8 update
Curly brace syntax in PHP?
I just discovered this browsing the PHP documentation inside a comment for goto : http://php.net/manual/en/control-structures.goto.php#92763 My question is, why does this work?
testing: < process: < die('Called'); >> // Displays 'Called'. goto process; // Doesn't work, syntax error goto testing.process;
What is this syntax called and is it ever utilized in PHP development? I can’t seem to find any documentation about this syntax, nor any examples. Any knowledge on the subject would be much appreciated!
A bit hard to find: php.net/manual/en/control-structures.intro.php They are just called «statement-group». They don’t really do anything.
I have been developing with PHP for nearly 4 years now, never have I found a use case that this will make sense in.
Probably its best use would be in php console scripts. Seems that the nesting structure does not work in the way you expect when you calling them. You just call the specific label.
Hi Steve, I’ve updated my answer with a concrete example of the usefulness of the goto operator. I hope it will be useful to you to better understand its use case.
3 Answers 3
In the goto documentation the target: syntax isn’t called anything, it just denotes a target for a goto to be able to jump to.
The curly braces don’t signify anything themselves, other than the code within belongs to that target. As in this comment, the braces just make the target syntax cleaner.
The target only has anything to do with the goto. The target isn’t (and can’t be) a variable and isn’t an object.
The . syntax in PHP is a string concatenation operator, since the testing and process targets aren’t strings, it throws an error saying the . was unexpected.
Since they aren’t objects either you wouldn’t be able to goto testing->process; since testing doesn’t own process , testing is just a target with another process target within it. You can call just goto testing; and Called will still be output.
Like everyone else is saying, please don’t use goto . It’s more harmful that it would be helpful.
Nothing wrong with the other answers, but this one explains everything perfectly along with my code example. Thanks @alec-gordon 😀
Braces in PHP are used simply to group statements into a block, which can be used in places where a single statement is required. For instance, when the body of if or while is multiple statements, you need to use braces to group them.
Other than that, they’re totally optional and have no effect on how the code runs. But editors will indent the code inside braces, so it can serve a self-documentation purpose to show related statements together.
That’s why they’re being used in the example you referenced. As the text says:
if you are not a fan of wild labels hanging around you are free to use braces in this construct creating a slightly cleaner look.
That’s the only purpose he has in using them, it’s just his personal style.
It’s not a common idiom ( goto in general is not common, so statement labels are rarely needed), and I’m not aware of any particular name for it.
I’ve used it sometimes in some edge cases (often to avoid nested if/else ).
But it has to be used very carefully.
I used it only to set the end of the script that were often a simple return .
Never use it to do complex things or your code will become messy very fast.
Here is the reference in the PHP documentation: goto
This is a concrete implementation where the use of goto was necessary to make the code readable and clean:
/** * @param \Exception $e * * @return bool|string Returns false in "production" if something goes wrong. * May return "retry" if rate limit is reached * * @throws ApiConnection Only in dev and test environments * @throws Authentication Only in dev and test environments * @throws Card Only in dev and test environments * @throws InvalidRequest Only in dev and test environments * @throws RateLimit Only in dev and test environments */ private function handleException(\Exception $e) < // If we received a rate limit exception, we have to retry with an exponential backoff if ($e instanceof RateLimit) < // If the maximum number of retries is already reached if ($this->retries >= $this->maxRetries) < goto raise; >// First, put the script on sleep sleep($this->wait); // Then we have to increment the sleep time $this->wait += $this->wait; // Increment by 1 the number of retries ++$this->retries; return 'retry'; > elseif ($e instanceof Card) < if ('dev' === $this->environment || 'test' === $this->environment) < throw $e; >return false; > // \Stripe\Error\Authentication, \Stripe\Error\InvalidRequest and \Stripe\Error\ApiConnection are raised immediately raise: $body = $e->getJsonBody(); $err = $body['error']; $message = '[' . $e->getHttpStatus() . ' - ' . $e->getJsonBody()['error']['type'] . '] ' . $e->getMessage(); $context = [ 'status' => $e->getHttpStatus(), 'type' => isset($err['type']) ? $err['type'] : '', 'code' => isset($err['code']) ? $err['code'] : '', 'param' => isset($err['param']) ? $err['param'] : '', 'request_id' => $e->getRequestId(), 'stripe_version' => $e->getHttpHeaders()['Stripe-Version'] ]; if (null === $this->logger) < $this->logger->error($message, $context); > if ('dev' === $this->environment || 'test' === $this->environment) < throw $e; >return false; >
This code manages the case of the raising of an exception by the Stripe SDK.
As you can see, if the max number of retries is reached, the code directly «jumps» to the raise tag.
This is a bundle for Symfony I maintain. Its full code is available here on GitHub.
Unexpected closing curly brace > error
I know this topic has been beaten into the ground, but I’m really stumped. I can’t figure out why I’m getting an unexpected > error. My problem is with a code snippet I’ve added to a Paypal credit card terminal script. It captures the form data into a MySql database so we can keep track of billing address information, etc. It works until I add an IF statement that is supposed to only send the data to MySQL if Paypal successfully successfully captures the card info. I want to do it this way because even if the form fails to capture the CC info, it will still be added to the database as if it were successful. Here’s the code. Again, it works until I add the if($ack=»SUCCESS») < and the corresponding closing brace at the end. If I remove the brace, I get an unexpected end error. What is the error? In Notepad++ everything looks like it matches up.
if($ack="SUCCESS") < $con = mysql_connect("localhost", "dbname", "dbpassword"); if (!$con) < die('Could not connect: ' . mysql_error()); >mysql_select_db("contributors", $con); $sql="INSERT INTO contributor_information (service, fname, lname, email, address, city, country, state, zip) VALUES ('$_POST[service]','$_POST[fname]','$_POST[lname]','$_POST[email]','$_POST[address]','$_POST[city]','$_POST[country]','$_POST[state]','$_POST[zip]')"; if (!mysql_query($sql,$con)) < die('Error: ' . mysql_error()); >mysql_close($con) >
Also. PLEASE do not put $_POST in your query like that. It’s bound to have all sorts of evilness in them. Use PDO parameterized queries.
“Array and string offset access syntax with curly braces is deprecated” – How To Fix It?
“Array and string offset access syntax with curly braces is deprecated” is a fairly common error that programmers can make. Don’t worry, this article will offer you some effective solutions to fix that error. First, let’s start with how it happened.
How does the error “Array and string offset access syntax with curly braces is deprecated” occur?
An array is a data structure containing several data values (all of which are of name same type) that a collection of multiple items can be stored under a single variable name. Furthermore, it also has members for performing common table operations.
The string is utilized to describe and manipulate a chain of characters. Strings play an important role in storing data that can be expressed in text form. Checking strings’ length, building and concatenating them, taking out substrings with the substring() method, or checking for the existence or position of substrings are some of the most common operations on strings
Array and string offset access syntax with curly braces is deprecated PHP Deprecated: Array and string offset access syntax with curly braces is deprecated in demo.php on line 99
Those are probably the error messages you’ll get when you’re trying to take value from the array with curly braces or debug a website that is enabled in PHP. Below are some solutions that we have learned and tried and we believe that one of them can help you fix the error “Array and string offset access syntax with curly braces is deprecated”.
How “Array and string offset access syntax with curly braces is deprecated” can be solved?
Solution 1: Access Array in PHP 7. X
The first method to fix the error “Array and string offset access syntax with curly braces is deprecated” is to access the array in PHP 7. X. The following array needs to be accessed only when you change to PHP 7. X from PHP 5. X.
Curly braces Fatal Errors after PHP 8 update
I’ve got a WordPress site that makes heavy use of a plugin, NextEnd Accordion Menu, which is no longer maintained. It still works great with each new version of WordPress and I’d like to stick to it if possible. But when I test a site update from PHP 7.3 to 8, the plugin breaks. Eventually I am going to have to go to PHP 8, so I’m trying to prepare for that time. I think I’ve found what needs to be fixed, as in the error logs I see fatal errors—«Array and string offset access syntax with curly braces is no longer supported.» When I look at the lines triggering the errors, I can see an easy fix for most of them. For four out of five of the errors, it’s just a matter of changing something like
if ($tag[0] == $this->lessc->vPrefix)
protected function end() < if ($this->literal(';')) < return true; >elseif ($this->count == strlen($this->buffer) || $this->buffercount> == '>') < // if there is end of file or a closing block next then we don't need a ; return true; >return false; >
That $this->buffercount> seems to be the offending item, but I am way beyond my depth in figuring out how to change it. I tried changing the curly braces to square braces, to parentheses, to double curly braces, and in each case it just caused more and different errors. Trying the square braces $this->buffer[$this->count] Gives me this more complicated and opaque to me new error:$this->
PHP Fatal error: Uncaught TypeError: array_merge(): Argument #2 must be of type array, null given in /nas/content/live/stagingsitexray/wp-content/plugins/nextend-accordion-menu/nextend/parse/font.php:27\nStack trace:\n#0 /nas/content/live/stagingsitexray/wp-content/plugins/nextend-accordion-menu/nextend/parse/font.php(27): array_merge(Array, NULL)\n#1 /nas/content/live/stagingsitexray/wp-content/plugins/nextend-accordion-menu/themes/default/default/context.php(39): NextendParseFont->mixinTab('Active')\n#2 /nas/content/live/stagingsitexray/wp-content/plugins/nextend-accordion-menu/library/accordionmenu/menu.php(161): include('/nas/content/li. ')\n#3 /nas/content/live/stagingsitexray/wp-content/plugins/nextend-accordion-menu/library/accordionmenu/wordpress/menu.php(67): NextendMenu->addCSS()\n#4 /nas/content/live/stagingsitexray/wp-content/plugins/nextend-accordion-menu/library/accordionmenu/menu.php(56): NextendMenuWordpress->addCSS()\n#5 /nas/content/live/stagingsitexray/wp-content/plugins/nextend-accordion-menu/widget.php(62): NextendMenu->render()\n#6 /nas/content/live/stagingsitexray/wp-includes/class-wp-widget.php(393): NextendAccordionMenuWidget->widget(Array, Array)\n#7 /nas/content/live/stagingsitexray/wp-includes/widgets.php(835): WP_Widget->display_callback(Array, Array)\n#8 /nas/content/live/stagingsitexray/wp-content/themes/customizr/sidebar-left.php(13): dynamic_sidebar('left')\n#9 /nas/content/live/stagingsitexray/wp-includes/template.php(770): require_once('/nas/content/li. ')\n#10 /nas/content/live/stagingsitexray/wp-includes/template.php(716): load_template('/nas/content/li. ', true, Array)\n#11 /nas/content/live/stagingsitexray/wp-includes/general-template.php(136): locate_template(Array, true, true, Array)\n#12 /nas/content/live/stagingsitexray/wp-content/themes/customizr/inc/czr-front-ccat.php(7650): get_sidebar('left')\n#13 /nas/content/live/stagingsitexray/wp-includes/class-wp-hook.php(307): CZR_sidebar->czr_fn_render_sidebar('')\n#14 /nas/content/live/stagingsitexray/wp-includes/class-wp-hook.php(331): WP_Hook->apply_filters('', Array)\n#15 /nas/content/live/stagingsitexray/wp-includes/plugin.php(476): WP_Hook->do_action(Array)\n#16 /nas/content/live/stagingsitexray/wp-content/themes/customizr/index.php(28): do_action('__before_articl. ')\n#17 /nas/content/live/stagingsitexray/wp-includes/template-loader.php(106): include('/nas/content/li. ')\n#18 /nas/content/live/stagingsitexray/wp-blog-header.php(19): require_once('/nas/content/li. ')\n#19 /nas/content/live/stagingsitexray/index.php(17): require('/nas/content/li. ')\n#20 \n thrown in /nas/content/live/stagingsitexray/wp-content/plugins/nextend-accordion-menu/nextend/parse/font.php on line 27, referer: https://stagingsitexray/wp-admin/edit.php?post_type=page
(those are a bunch of other files, not the one I’m currently editing, which is /nas/content/live/stagingsitexray/wp-content/plugins/nextend-accordion-menu/nextend/css/less.php