【问题标题】:PHP global variable scope usage best practisePHP 全局变量范围使用最佳实践
【发布时间】:2018-04-18 21:46:21
【问题描述】:

我是编程新手,对函数内部全局变量的使用有些怀疑。

我试图将逻辑与我的 html 表单的结构分开,这就是我的问题的来源。

我声明为全局的变量只会在函数外部的一个特定位置使用,即 html 表单。

function updatePosts(){
     $query= "...";
     $result= "...";
     $rows= mysqli_fetch_assoc($result);
     global $post_title;
     $post_title = $rows['post_title'] ;
}

updatePosts();

<form action="">
//use of global variable outside function
    <input type="text" name="" value="{$post_title}" class="form-control">
</form>

当我声明多个全局变量时,它提出了一些关于这么多全局变量的影响可能是什么的问题。例如。

function updatePosts(){
     $query= "...";
     $result= "...";
     $rows= mysqli_fetch_assoc($result);
     global $post_title;
     global $post_author;
     global $post_content;
     global $post_tags;
     global $post_image;
     global $post_status;
     global $post_date;
     $post_title = $rows['post_title'] ;
     $post_author = $rows['post_author'] ;
     $post_content = $rows['post_content'] ;
     $post_tags = $rows['post_tags'] ;
     $post_image = $rows['post_image'] ;
     $post_status = $rows['status'] ;
     //and so on..
}

updatePosts();

<form action="">
<input type="text" name="" value="<?php echo $post_title ?>" class="form-control">
<input type="text" name="" value="<?php echo $post_author ?>" class="form-control">
<input type="text" name="" value="<?php echo $post_tags ?>" class="form-control">
<input type="text" name="" value="<?php echo $post_content ?>" class="form-control">
<input type="text" name="" value="<?php echo $post_status ?>" class="form-control">
//and so on...
</form>

这被认为是函数和全局变量的可接受用法吗?

如果不是,那么将逻辑与结构分离的更有效方法可能是什么。而不是封装在一个函数中,includes 会更适合这个任务吗?

任何建议都将不胜感激,并将在帮助初学者在编程/php 之旅中大有帮助。

【问题讨论】:

标签: php variables scope


【解决方案1】:

我个人会使用 闭包 来获取范围内的变量以供进一步使用,是的,关键字 global 是不好的做法,在旧版本中它在程序编码中更有用,但今天你只是构建微小的闭包以供快速使用。

只是给你一个大致的想法。

$variable_from_outside = "hi!";
$closure = function() use ($variable_from_outside) {
    // do stuff with that variable inside this scope..
};

Closure Documentation

但是,您也可以只在函数中获取变量作为参数

$variable = 'something';
function func($variable) {
    // do stuff with $variable
}

在 OOP 中,最好的方法是 Traits。声明通用属性或方法,并在类中use 他们随心所欲。此外,当您在以后的派生类中采用特征时,它也会降低性能,例如,它们不必一直在您的整个 API 中携带。

trait Example {
    public $stuff = 'Yey!';
    // or methods...
}

class someClass {
    use Example;
    function __construct() {
        echo $this->stuff; // Yey!
        // etc...
    }
}

Trait Documentation

【讨论】:

  • 非常感谢您的帮助,我仍在学习并且(非常期待)我还没有接触到诸如 OOP 和闭包之类的主题。我一定会进一步阅读这些主题。感谢您的宝贵时间和非常有见地的回答。我希望能彻底阅读您的解释,理解并选择它作为正确答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-19
  • 1970-01-01
  • 2013-03-15
  • 1970-01-01
  • 2016-07-23
  • 1970-01-01
  • 2013-05-26
相关资源
最近更新 更多