您的位置 首页 php

PHP新手如何提高代码质量

1.不要使用相对路径

常常会看到:

require_once('../../lib/some_>
 

该方法有很多缺点:

它首先查找指定的php包含路径, 然后查找当前目录.

因此会检查过多路径.

如果该脚本被另一目录的脚本包含, 它的基本目录变成了另一脚本所在的目录.

另一问题, 当定时任务运行该脚本, 它的上级目录可能就不是工作目录了.

因此最佳选择是使用绝对路径:

define('ROOT' , '/var/www/project/');
require_once(ROOT . '../../lib/some_>
 

我们定义了一个绝对路径, 值被写死了. 我们还可以改进它. 路径 /var/www/project 也可能会改变, 那么我们每次都要改变它吗? 不是的, 我们可以使用__FILE__常量, 如:

//suppose your script is /var/www/project/index.php
//Then __FILE__ will always have that full path.

define('ROOT' , pathinfo(__FILE__, PATHINFO_DIRNAME));
require_once(ROOT . '../../lib/some_>
 

现在, 无论你移到哪个目录, 如移到一个外网的服务器上, 代码无须更改便可正确运行.

2. 不要直接使用 require, include, include_once, required_once

可以在脚本头部引入多个文件, 像类库, 工具文件和助手函数等, 如:

require_once('lib/Database.php');
require_once('lib/Mail.php');
require_once('helpers/utitlity_functions.php'); 

这种用法相当原始. 应该更灵活点. 应编写个助手函数包含文件. 例如:

function load_>
 

有什么不一样吗? 该代码更具可读性.

將来你可以按需扩展该函数, 如:

function load_>
 

还可做得更多:

为同样文件查找多个目录

能很容易的改变放置类文件的目录, 无须在代码各处一一修改

可使用类似的函数加载文件, 如html内容.

3. 为应用保留调试代码

在开发环境中, 我们打印数据库查询语句, 转存有问题的变量值, 而一旦问题解决, 我们注释或删除它们. 然而更好的做法是保留调试代码.

在开发环境中, 你可以:

define('ENVIRONMENT' , 'development');

if(! $db->query( $query )
{
    if(ENVIRONMENT == 'development')
    {
        echo "$query failed";
    }
    else
    {
        echo "Database error. Please contact administrator";
    }
} 

在服务器中, 你可以:

define('ENVIRONMENT' , 'production');

if(! $db->query( $query )
{
    if(ENVIRONMENT == 'development')
    {
        echo "$query failed";
    }
    else
    {
        echo "Database error. Please contact administrator";
    }
} 

4. 使用可跨平台的函数执行命令

system, exec, passthru, shell_exec 这4个函数可用于执行系统命令. 每个的行为都有细微差别. 问题在于, 当在共享主机中, 某些函数可能被选择性的禁用. 大多数新手趋于每次首先检查哪个函数可用, 然而再使用它.

更好的方案是封成函数一个可跨平台的函数.

/**
	Method to execute a command in the terminal
	Uses :

	1. system
	2. passthru
	3. exec
	4. shell_exec

*/
function terminal($command)
{
	//system
	if(function_exists('system'))
	{
		ob_start;
		system($command , $return_var);
		$output = ob_get_contents;
		ob_end_clean;
	}
	//passthru
	else if(function_exists('passthru'))
	{
		ob_start;
		passthru($command , $return_var);
		$output = ob_get_contents;
		ob_end_clean;
	}

	//exec
	else if(function_exists('exec'))
	{
		exec($command , $output , $return_var);
		$output = implode("n" , $output);
	}

	//shell_exec
	else if(function_exists('shell_exec'))
	{
		$output = shell_exec($command) ;
	}

	else
	{
		$output = 'Command execution not possible on this system';
		$return_var = 1;
	}

	return array('output' => $output , 'status' => $return_var);
}
terminal('ls'); 

上面的函数將运行shell命令, 只要有一个系统函数可用, 这保持了代码的一致性.

5. 灵活编写函数

function add_to_cart($item_id , $qty)
{
    $_SESSION['cart']['item_id'] = $qty;
}

add_to_cart( 'IPHONE3' , 2 ); 

使用上面的函数添加单个项目. 而当添加项列表的时候,你要创建另一个函数吗? 不用, 只要稍加留意不同类型的参数, 就会更灵活. 如:

function add_to_cart($item_id , $qty)
{
    if(!is_array($item_id))
    {
        $_SESSION['cart']['item_id'] = $qty;
    }

    else
    {
        foreach($item_id as $i_id => $qty)
        {
 $_SESSION['cart']['i_id'] = $qty;
        }
    }
}

add_to_cart( 'IPHONE3' , 2 );
add_to_cart( array('IPHONE3' => 2 , 'IPAD' => 5) ); 

现在, 同个函数可以处理不同类型的输入参数了. 可以参照上面的例子重构你的多处代码, 使其更智能.

6. 有意忽略php关闭标签

我很想知道为什么这么多关于php建议的博客文章都没提到这点.

 

这將节约你很多时间. 我们举个例子:

一个 super_>

//super extra character after the closing tag 

index.php

require_once('super_>
 

这样, 你將会得到一个 Headers already send error. 为什么? 因为 “super extra character” 已经被输出了. 现在你得开始调试啦. 这会花费大量时间寻找 super extra 的位置.

因此, 养成省略关闭符的习惯:

文章来源:智云一二三科技

文章标题:PHP新手如何提高代码质量

文章地址:https://www.zhihuclub.com/77844.shtml

关于作者: 智云科技

热门文章

评论已关闭

48条评论

  1. In 1998, the US Food and Drug Administration FDA approved the little blue pill for treating ED McMurray, 2007 There was less clinical worsening defined as death, lung transplantation, atrial septostomy, hospitalization because of worsening PAH, initiation of new PAH therapy prostacyclin or analog, endothelin receptor antagonist, PDE5 inhibitor , or worsening WHO functional class in the tadalafil 40 mg group compared to the placebo group and the groups that used lower doses of tadalafil

  2. Monitor Closely 1 tadalafil increases effects of eplerenone by pharmacodynamic synergism

  3. Huawei did not say anything, just smiled naively, and continued to build CPUs amidst the abuse and questioning Master of Samatha Mcnaught, master of Samatha Volkman

  4. 15,16 A similar effect of tadalafil concerning increasing tissue perfusion and oxygenation has also been described in an animal model of severe neurogenic ED; chronic treatment with tadalafil after bilateral cavernous nerve neurotomy in the rat normalized penile oxygenation as well as smooth muscle content

  5. However, beginners should avoid taking it with harsh compounds such as Anadrol, trenbolone, Winstrol, etc. Been ttc for women who, you are not that i have more about 10 of pills.

  6. If you do not have regular, or have very infrequent periods, you will be given a progestin such as Provera to induce bleeding.

  7. Your dog s regular dry food can make a great healthy dog treat Peanut butter Pumpkin Apple slices Fresh vegetables AdVENTuROS dog treats. Antibiotic prescription for abscesses.

  8. If your water has higher levels of fluoride than normal, you can minimize consumption when your baby is young by breastfeeding, using non- fluoridated water for mixing with formula powder or concentrate, or buying prepared formula. Vandermolen is compassionate towards your situation.

  9. Palliative therapy is given to improve quality of life and prolong survival when no cure is possible 40

  10. Women who have had breast cancer should follow the general recommendation from the National Osteoporosis Foundation first bone density test at 65 or at the end of therapy Exogenous MCSF 40 Ојg kg of body weight intraperitoneally i

  11. Terry Mamounas Of course in that update as well as the previous update, we did not show a survival benefit is on the Scientific Advisory Boards of Labcorp, Inc

  12. The first place can be like Zhao Ling to ask about alchemy, what do you think After Yun Yuanlang finished speaking, he looked at the fifty alchemists with a smile Trends Pharmacol Sci 2009; 30 515 27

  13. PubMed 16256740 CrossRef Randomization was stratified by world region United States, Western Europe, other, number of prior chemotherapy regimens for unresectable locally advanced or metastatic disease 0 1, 1 and visceral versus non visceral disease as determined by the investigators

  14. Targeted expression of Cre recombinase provokes cardiac restricted, site specific rearrangement in adult ventricular muscle in vivo Silencing TFRC, the gene encoding TFR 1, can inhibit erastin induced ferroptosis 25, while heme oxygenase 1 HO 1 can accelerate erastin induced ferroptosis by supplementing iron 26

  15. We have shown that HOXB13 is predictive of response to adjuvant tamoxifen therapy, in terms of a longer DRFS and BCS for tamoxifen treated breast cancer patients if the protein expression is low or absent Biochim Biophys Acta, 1332, F105 F126

  16. ruagra benzoyl peroxide para que sirve Five star hotel lobbies in the capital Luanda bubble withtalk of deals to profit from the country s economic success, with the government adding to the lure by announcing plans for a 5 billion sovereign wealth fund, a bourse and a Eurobond

  17. Etoposide is highly active for the treatment of lymphoma, and has demonstrated marked activity as a component of several salvage regimens

  18. Therefore, glutamine addiction helps cancer cells to acquire substrates for rapid proliferation and to survive better in complex environments

  19. value or large Chi- sqaure statistic relative to the degree of freedom indicates heterogeneity

  20. Briefly, cells were washed in phosphate buffered saline, fixed in cold 4 paraformaldehyde, washed again, and then permeabilized with

  21. I found some Melatonin Plus at Costco it s 3 mg of melatonin with 25 mg of Theanine, which is apparently a natural compound found in green tea that has calming and stress relief properties

  22. Her choices come down to Tamoxifen or AIs Femara, Aromasin, or Arimidex The above image shows the two different forms of glucose molecule as their Fischer projection

  23. BREAST CANCER RISK FACTORS The FDA has approved tamoxifen to reduce the incidence of breast cancer in women at high risk of the disease DAPK1 IT1 20 GO terms 17 in BP, 3 in MF, 3 KEGG pathways, 6 REACTOME_Pathways, and 4 Wiki_pathways

  24. These end points will provide more informative data on cancer progression and therapeutic effect eg, comparison of in field versus out of field recurrences

  25. In premenopause, there is not a statistically significant difference in the incidence of EC in patients treated or untreated with tamoxifen So, I have scheduled an appointment with a dr who uses mini- IVF for poor responders

  26. In dogs with experimental gastric dilation and torsion, flunixin did not alter cardiac indices or blood flows significantly but did reduce prostacyclin levels, suggesting that it may attenuate or inhibit the continued effects of endotoxic damage

网站地图