5 流程控制语句

作者:老葛,北京亚艾元软件有限责任公司,http://www.yaiyuan.com

流程控制语句是程序中用来控制执行流程的指令,比如条件语句和循环语句。条件语句有ifelse elseif、和switch语句。循环语句有whiledo-whileforforeach

 

流程控制语句在关键字(ifelseif、 whilefor, 等等)和开括号之间应有一个空格,从而将其与函数调用(也使用圆括号,但是没有空格)区分开来。“{”应该与关键字位于同一行(而不是自成一行),这一点对于很多熟悉PHP的程序员来说,开始的时候可能很不适应,但这就是Drupal的规范,它与PHP的规范还是有区别的。“}”应该自成一行。

    下面的这段代码摘自node.modulenode_block_list_alter函数:

 

if (!empty($node)) {

// This is a node or node edit page.

if (!isset($block_node_types[$block->module][$block->delta][$node->type])) {

// This block should not be displayed for this node type.

unset($blocks[$key]);

continue;

}

}

elseif (isset($node_add_arg) && isset($node_types[$node_add_arg])) {

// This is a node creation page

if (!isset($block_node_types[$block->module][$block->delta][$node_add_arg])) {

// This block should not be displayed for this node type.

unset($blocks[$key]);

continue;

}

}

else {

// This is not a node page, remove the block.

unset($blocks[$key]);

continue;

}

花括号“{}”一般总是使用的,即便是不需要的时候,为了增强代码的可读性,并降低出错的可能性,也应使用“{}”。下面的正确代码摘自于代码摘自node.modulenode_mark函数。

 

错误的

if (!$user->uid)

  return MARK_READ;

正确的

if (!$user->uid) {

return MARK_READ;

}

切换语句的格式应该这样(注意break;”语句在默认情况下不是必需的),摘自于代码摘自node.modulenode_block_view函数

switch ($delta) {

case 'syndicate':

$block['subject'] = t('Syndicate');

$block['content'] = theme('feed_icon', array('url' => 'rss.xml', 'title' => t('Syndicate')));

break;

 

case 'recent':

if (user_access('access content')) {

$block['subject'] = t('Recent content');

if ($nodes = node_get_recent(variable_get('node_recent_block_count', 10))) {

$block['content'] = theme('node_recent_block', array(

'nodes' => $nodes,

));

} else {

$block['content'] = t('No content available.');

}

}

break;

}

当一个情况执行完以后,打算继续执行下一情况时,此时可以省略“break;”语句。


Drupal版本: