简体   繁体   English

如何从 PHP 中的另一个包含文件中引用变量?

[英]How can I reference variables from another included file in PHP?

So I'm working on a PHP app and trying to make everything moduler.所以我正在开发一个 PHP 应用程序,并试图让一切变得更模块化。 I have an index.php file that includes other php files.我有一个 index.php 文件,其中包括其他 php 文件。 The first file included is settings.php which has my postgres credentials defined so they can be accessed elsewhere.包含的第一个文件是 settings.php 定义了我的 postgres 凭据,以便可以在其他地方访问它们。 The second file is connect.php that has a function you can pass sql to and it will return $result.第二个文件是connect.php,它有一个function,你可以将sql传递给它,它会返回$result。 The third file has functions that call the sql function and receive $result and parse it.第三个文件具有调用 sql function 并接收 $result 并解析它的函数。 In the third file, I can read the results of the $result however if I try if($result) it breaks and isset/empty have no effect.在第三个文件中,我可以读取 $result 的结果,但是如果我尝试 if($result) 它会中断并且 isset/empty 无效。

Anyone have any ideas on a way to make this work, or is my structure just terrible?有人对如何使这项工作有任何想法,还是我的结构很糟糕?

Thanks so much!非常感谢!

Mike麦克风

let's say you have the following three files:假设您有以下三个文件:

inc1.php inc1.php

<?php
  $foo = 'hello';
?>

inc2.php inc2.php

<?php
  echo $foo;
?>

main.php main.php

include('inc1.php');
include('inc2.php');

it should echo "hello".它应该回显“你好”。 however, passing variables around among files is a bad idea, and can lead to a lot of confusing, hard-to-follow code.但是,在文件之间传递变量是一个坏主意,并且会导致很多混乱、难以理解的代码。 If you need to pass variables around, use functions and/or objects so that you can at least see where they are coming from.如果您需要传递变量,请使用函数和/或对象,以便您至少可以看到它们的来源。

beyond that though, it's difficult to tell exactly what your problem is without seeing the code in question.除此之外,如果没有看到有问题的代码,很难准确地判断您的问题是什么。

I would really try to switch to OOP.我真的会尝试切换到 OOP。 This makes things a lot of easier.这让事情变得容易多了。 If you just have to deal with classes, their methods and attributes you only have to include the classes and not this choas of functions.如果你只需要处理类、它们的方法和属性,你只需要包含类而不是这些函数。 So I would recommend, give it a go...所以我建议,给它一个 go ...

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

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