【发布时间】: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 之旅中大有帮助。
【问题讨论】:
-
数据应该通过使用函数参数和返回值跨函数边界来回传递。从您发布的摘录中很难说,但您可能正在寻找一个函数来返回一个或多个帖子(作为对象或只是数组),然后您可以将其传递给您的显示层,而不是设置它们全局范围。
-
返回一个数组或对象,它将所有这些变量捆绑到一个东西中;也许你应该直接
return $rows。 -
不应该在Code Review 上问这个问题吗?在我看来,问题是关于改进工作代码。
-
@GrumpyCrouton 谢谢,我会阅读链接