简体   繁体   English

PHP函数全局与需求

[英]PHP Function Global vs. Require

I have a script that runs based on variables in another script. 我有一个基于另一个脚本中的变量运行的脚本。 At the top of the script, I require the variables script. 在脚本的顶部,我需要变量脚本。

I am trying to make my script easier to edit so I decided to create functions because a lot of my scripts do the exact same thing. 我试图使脚本的编辑更容易,所以我决定创建函数,因为我的许多脚本都做同样的事情。 In the functions, I need to pull some of the variables set in the variable script. 在函数中,我需要提取在变量脚本中设置的一些变量。 I tried using require and it tends to make the script very slow. 我尝试使用require,这会使脚本非常慢。 I know I can set PHP globals but I read somewhere that using globals is a bad idea? 我知道我可以设置PHP全局变量,但是我读到某个地方说使用全局变量是个坏主意? Is this true? 这是真的?

Is there a better way to do this besides using a require in the function or using globals? 除了在函数中使用require或使用Globals之外,还有更好的方法吗?

Code: 码:

function test() 
{
    require('var.php');

    // function code
}

OR 要么

require('var.php');

function test() 
{
    global $var_variable1, $var_variable2;

    // function code
}

There is actually third option: 实际上还有第三种选择:

in file param.php 在文件param.php中

<?php
    $param = 1234;
?>

in file test.php 在文件test.php中

<?php

    require 'param.php';

    function foo( $bar )
    {
        var_dump( $bar );
    }

    foo( $param );

?>

But you should understand , that this is a very primitive way of dealing with variables and passing instructions from one piece of code to another. 但是您应该了解,这是一种非常原始的处理变量并将指令从一段代码传递到另一段代码的方法。

When you are done with learning the basics of PHP language, you should start investigating Object Oriented programming methodology. 学习完PHP语言的基础知识后,您应该开始研究面向对象的编程方法。 That would be the way to grow. 那将是增长的方式。

When variables are fixed, it's a good solution to use constants. 固定变量后,使用常量是一个很好的解决方案。

Create a PHP file with all your constants: 使用所有常量创建一个PHP文件:

<?php
define("FOO",     "something");
define("FOO2",    "someotherthing");
?>

By convention use UPPERCASE constant names. 按照约定,使用大写常量名称。 Into your script files use require_once() as the first line to include your script file where you define all your constants. 在脚本文件中,使用require_once()作为第一行,以包括在其中定义所有常量的脚本文件。

Do the same with a script containing all your support functions and require_once the file from your scripts. 使用包含所有支持功能的脚本执行相同的操作,并从脚本中要求文件。

If possible use OOP with PHP. 如果可能,请对PHP使用OOP。 With objects you can do very cool things. 使用对象,您可以做很酷的事情。

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

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