简体   繁体   English

PHP require_once在我的代码中不起作用

[英]PHP require_once not working in my code

this is probably a basic question about php, but I can't figure out how to solve it. 这可能是关于php的一个基本问题,但是我不知道如何解决它。

Well, I have a file called globals.php 好吧,我有一个名为globals.php的文件

<?php
$DATA = array(
    'first' => 'LOL',
    'second' => 'Whatever'
);
?>

And I also have another file (omg.php) with the following function: 而且我还有另一个具有以下功能的文件(omg.php):

<?php

require_once('globals.php');

function print_text_omg($selector = 0){
global $DATA; //added this line of code. NOW IT WORKS
$var = '';
if($selector == 0){
    $var = '';
}else{
    $var = 'Hi. ';
}

//$DATA is a variable from globals.php that is supposed to be declared in require_once('globals.php');
//$var is a variable inside the function print_text_omg
//I am trying to concatenate string $var with the string $DATA['first']

$finaltext = $var.$DATA['first'];
echo $finaltext;
}
?>

Then, in main.php I have this: 然后,在main.php中,我有这个:

<?php 
include('omg.php');
print_text_omg();
print_text_omg(1);
?>

This should print something like: 这应该打印类似:

//LOL
//Hi. LOL

Instead, I have this warning: 相反,我有此警告:

Notice: Undefined variable: DATA in ... 注意:未定义变量:DATA in ...

Which is the part of $finaltext = $var.$DATA['first']; 这是$finaltext = $var.$DATA['first'];

UPDATE UPDATE

Thanks to user Casimir et Hippolyte' suggestion, I've edited my function and it works now. 感谢用户Casimir et Hippolyte的建议,我已经编辑了功能,现在可以使用了。 Added the line that worked for me. 添加了对我有用的行。

It doesn't work because $DATA isn't in the scope of your function. 它不起作用,因为$DATA不在函数范围内。

To make $DATA available inside your function, you must pass it as a parameter to the function or define $DATA as a global variable. 要使$DATA在函数内部可用,必须将其作为参数传递给函数或将$DATA定义为全局变量。

The problem isn't related to require_once . 问题与require_once无关。

http://php.net/manual/en/language.variables.scope.php http://php.net/manual/en/language.variables.scope.php

The error is correct, first I can't find where did you declare $var (maybe it should be an object of some class?) and also $var doesn't contain the $DATA array, and for last, . 错误是正确的,首先我找不到在哪里声明$var (也许应该是某个类的对象?),而且$var不包含$ DATA数组,最后是. operator in php is for concatenate strings, for object navigation is -> operator php中的运算符用于连接字符串,对象导航是->运算符

You haven't declared the variable $var , plus . 您尚未声明变量$var和plus . is php's concatenation operator. 是php的串联运算符。 Try changing your code to this 尝试将代码更改为此

$finaltext = $DATA['first'] ; $finaltext = $DATA['first'] ;

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

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