Parse error unexpected ":" Works fine in localhost

I have a PHP application with me, which was done by myself and a few of us. I have not coded much, but it worked well in the localhost . When I tried to upload it in our university web server, I had got this error.

Parse error unexpected :

This happened on this line. So I believe that PHP has to do something with respect to the previous line too. So I am adding the previous and next lines:

<?php
  session_start();
  $page = $_GET["page"] ?: "index"; // Error in this line!

The funny part is, this works on my WAMP Server locally, but it doesn't work in the university server. Is there any issue with the code?


I believe the PHP in your University Web Server is very old or older than 5.3 . This is a shorthand ternary operator and is supported by PHP versions 5.3 and above.

Workaround

$page = $_GET["page"] ? $_GET["page"] : "index";

Update: To remove the warning, where $_GET["page"] is not set, you can use:

$page = isset($_GET["page"]) ? $_GET["page"] : "index"; // Checks if $_GET["page"] exists, and then assigns it.

PHP 7 will allow to use this short syntax:

$page = $_GET["page"] ?? "index";

From the docs:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.


Quoting from the PHP Docs

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

I suggest that your university should update their servers to a supported version of PHP


The problem may be the version of PHP.

Maybe your PHP version local is higher than in your university server.

You must see in which version from PHP ?: works

链接地址: http://www.djcxy.com/p/11942.html

上一篇: 双引号不能正常复制。 我如何编辑它们?

下一篇: 解析错误意外“:”在localhost中正常工作