简体   繁体   English

尝试使用 function 时出现 PHP 语法错误

[英]PHP Syntax Error when trying to use a function

Recently I started working with PHP and creating functions to make stuff easier for me.最近我开始使用 PHP 并创建函数让我的工作更轻松。

I just created a simple function that I can use in a lot of files so it checks the users 'permission group' (eg Admin).我刚刚创建了一个简单的 function,我可以在很多文件中使用它,因此它会检查用户的“权限组”(例如管理员)。

This is the code that was used:这是使用的代码:

function staffCheckStart() {
    echo "if ($_SESSION['role'] == 'Admin' OR $_SESSION['role'] == 'Owner'):";
}

function staffCheckEnd() {
    echo "endif";
}

This is how the function is called in another document.这就是 function 在另一个文档中的调用方式。

<?php staffCheckStart(); ?>
        
   <iframe src="gif.com" width="276" height="480" frameBorder="0" class="giphy-embed" allowFullScreen></iframe><p><a href="gif.com">via GIPHY</a></p>

<?php staffCheckEnd(); ?>

And in return I get this error.作为回报,我得到了这个错误。

In my head this all works out because I just want the code to echo the PHP line that I've written in my function.在我的脑海中,这一切都解决了,因为我只想让代码显我在 function 中编写的 PHP 行。 The only reason I tried to use functions is because I first of all want to make it easier and make the code look clean as writing things like this over and over really drives me insane.我尝试使用函数的唯一原因是因为我首先想让它更容易并使代码看起来干净,因为一遍又一遍地编写这样的东西真的让我发疯。 It returns me a syntax error but I have no clue what it is.它返回给我一个语法错误,但我不知道它是什么。

First, you can't echo PHP code to browser to work, it just make code like string.首先,您不能将 PHP 代码回显到浏览器以使其正常工作,它只会使代码像字符串一样。 Second, from what I saw in your code, I think you want show iframe when role is "Admin" or "Owner".其次,根据我在您的代码中看到的内容,我认为您希望在角色为“管理员”或“所有者”时显示iframe So, I suggest you to make like this所以,我建议你这样做

<?php if ($_SESSION['role'] == 'Admin' OR $_SESSION['role'] == 'Owner'): ?>
        
   <iframe src="gif.com" width="276" height="480" frameBorder="0" class="giphy-embed" allowFullScreen></iframe><p><a href="gif.com">via GIPHY</a></p>

<?php endif; ?>

Echoing PHP code will not substitute the code back into the script to be executed.回显 PHP 代码不会将代码替换回要执行的脚本中。 So your whole approach is misguided.所以你的整个方法是错误的。

The function should return the result of the condition, and then you can call it in an ordinary if statement. function应该返回条件的结果,然后你可以在普通的if语句中调用它。

<?php
function staffCheck() {
    return $_SESSION['role'] == 'Admin' OR $_SESSION['role'] == 'Owner';
}

if ($staffCheck()): ?>
   <iframe src="gif.com" width="276" height="480" frameBorder="0" class="giphy-embed" allowFullScreen></iframe><p><a href="gif.com">via GIPHY</a></p>
<?php endif; ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM