php语言

对初学者非常有用的PHP技巧

时间:2022-11-16 12:47:27 php语言 我要投稿
  • 相关推荐

对初学者非常有用的PHP技巧

  文章主要为大家详细介绍了10个对初学者非常有用的PHP技巧,这些PHP技巧适用于初学者,而不是那些已经在使用MVC框架的人,感兴趣的小伙伴们可以参考一下。

  本文介绍一些关于改善和优化PHP代码的提示和技巧,供大家参考,具体内容如下

  1.不要使用相对路径,要定义一个根路径

  这样的代码行很常见:

  ?

  1

  require_once('../../lib/some_class.php');

  这种方法有很多缺点:

  1)、它首先搜索php包括路径中的指定目录,然后查看当前目录。因此,会检查许多目录。

  2)、当一个脚本被包含在另一个脚本的不同目录中时,它的基本目录变为包含脚本的目录。

  3)、另一个问题是,当一个脚本从cron运行时,它可能不会将它的父目录作为工作目录。

  所以使用绝对路径便成为了一个好方法:

  ?

  1

  2

  3

  4

  define('ROOT' , '/var/www/project/');

  require_once(ROOT . '../../lib/some_class.php');

  //rest of the code

  这就是一个绝对路径,并且会一直保持不变。但是,我们可以进一步改善。目录/var/www/project可以变,那么我们每次都要改吗?

  不,使用魔术常量如__FILE__可以让它变得可移植。请仔细看:

  ?

  1

  2

  3

  4

  5

  6

  7

  //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_class.php');

  //rest of the code

  所以现在,即使你将项目转移到一个不同的目录,例如将其移动到一个在线的服务器上,这些代码不需要更改就可以运行。

  2.不使用require,包括require_once或include_once

  你的脚本上可能会包括各种文件,如类库,实用程序文件和辅助函数等,就像这些:

  ?

  1

  2

  3

  4

  require_once('lib/Database.php');

  require_once('lib/Mail.php');

  require_once('helpers/utitlity_functions.php');

  这相当粗糙。代码需要更加灵活。写好辅助函数可以更容易地包含东西。举个例子:

  ?

  1

  2

  3

  4

  5

  6

  7

  8

  9

  function load_class($class_name)

  {

  //path to the class file

  $path = ROOT . '/lib/' . $class_name . '.php');

  require_once( $path );

  }

  load_class('Database');

  load_class('Mail');

  看到区别了吗?很明显。不需要任何更多的解释。

  你还可以进一步改善:

  ?

  1

  2

  3

  4

  5

  6

  7

  8

  9

  10

  function load_class($class_name)

  {

  //path to the class file

  $path = ROOT . '/lib/' . $class_name . '.php');

  if(file_exists($path))

  {

  require_once( $path );

  }

  }

  这样做可以完成很多事情:

  为同一个类文件搜索多个目录。

  轻松更改包含类文件的目录,而不破坏任何地方的代码。

  使用类似的函数用于加载包含辅助函数、HTML内容等的文件。

  3.在应用程序中维护调试环境

  在开发过程中,我们echo数据库查询,转储创造问题的变量,然后一旦问题被解决,我们注释它们或删除它们。但让一切留在原地可提供长效帮助。

  在开发计算机上,你可以这样做:

  ?

  1

  2

  3

  4

  5

  6

  7

  8

  9

  10

  11

  12

  13

  define('ENVIRONMENT' , 'development');

  if(! $db->query( $query )

  {

  if(ENVIRONMENT == 'development')

  {

  echo "$query failed";

  }

  else

  {

  echo "Database error. Please contact administrator";

  }

  }

  并且在服务器上,你可以这样做:

  ?

  1

  2

  3

  4

  5

  6

  7

  8

  9

  10

  11

  12

  13

  define('ENVIRONMENT' , 'production');

  if(! $db->query( $query )

  {

  if(ENVIRONMENT == 'development')

  {

  echo "$query failed";

  }

  else

  {

  echo "Database error. Please contact administrator";

  }

  }

  4.通过会话传播状态消息

  状态消息是那些执行任务后生成的消息。

  ?

  1

  2

  3

  4

  5

  6

  7

  8

  9

  10

  11

  12

  13

  14

  15

  16

  <?php

  if($wrong_username || $wrong_password)

  {

  $msg = 'Invalid username or password';

  }

  ?>

  <html>

  <body>

  <?php echo $msg; ?>

  <form>

  ...

  </form>

  </body>

  </html>

  这样的代码很常见。使用变量来显示状态信息有一定的局限性。因为它们无法通过重定向发送(除非你将它们作为GET变量传播给下一个脚本,但这非常愚蠢)。而且在大型脚本中可能会有多个消息等。

  最好的办法是使用会话来传播(即使是在同一页面上)。想要这样做的话在每个页面上必须得有一个session_start。

  ?

  1

  2

  3

  4

  5

  6

  7

  8

  9

  10

  11

  function set_flash($msg)

  {

  $_SESSION['message'] = $msg;

  }

  function get_flash()

  {

  $msg = $_SESSION['message'];

  unset($_SESSION['message']);

  return $msg;

  }

  在你的脚本中:

  ?

  1

  2

  3

  4

  5

  6

  7

  8

  9

  10

  11

  12

  13

  14

  15

  <?php

  if($wrong_username || $wrong_password)

  {

  set_flash('Invalid username or password');

  }

  ?>

  <html>

  <body>

  Status is : <?php echo get_flash(); ?>

  <form>

  ...

  </form>

  </body>

  </html>

  5.让函数变得灵活

  ?

  1

  2

  3

  4

  5

  6

  function add_to_cart($item_id , $qty)

  {

  $_SESSION['cart'][$item_id] = $qty;

  }

  add_to_cart( 'IPHONE3' , 2 );

  当添加单一条目时,使用上面的函数。那么当添加多个条目时,就得创建另一个函数吗?NO。只要让函数变得灵活起来使之能够接受不同的参数即可。请看:

  ?

  1

  2

  3

  4

  5

  6

  7

  8

  9

  10

  11

  12

  13

  14

  15

  16

  17

  18

  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小技巧时要省略这个技巧。

  ?

  1

  2

  3

  4

  5

  <?php

  echo "Hello";

  //Now dont close this tag

  这可以帮助你省略大量问题。举一个例子:

  类文件super_class.php

  ?

  1

  2

  3

  4

  5

  6

  7

  8

  9

  10

  <?php

  class super_class

  {

  function super_function()

  {

  //super code

  }

  }

  ?>

  //super extra character after the closing tag

  现在看index.php

  ?

  1

  2

  3

  require_once('super_class.php');

  //echo an image or pdf , or set the cookies or session data

  你会得到发送错误的Header。为什么呢?因为“超级多余字符”,所有标题都去处理这个去了。于是你得开始调试。你可能需要浪费很多时间来寻找超级额外的空间。

  因此要养成省略结束标签的习惯:

  ?

  1

  2

  3

  4

  5

  6

  7

  8

  9

  10

  <?php

  class super_class

  {

  function super_function()

  {

  //super code

  }

  }

  //No closing tag

  这样更好。

  7.在一个地方收集所有输出,然后一次性输出给浏览器

  这就是所谓的输出缓冲。比方说,你从不同的函数得到像这样的内容:

  ?

  1

  2

  3

  4

  5

  6

  7

  8

  9

  10

  11

  12

  13

  14

  15

  16

  function print_header()

  {

  echo "<p id='header'>Site Log and Login links</p>";

  }

  function print_footer()

  {

  echo "<p id='footer'>Site was made by me</p>";

  }

  print_header();

  for($i = 0 ; $i < 100; $i++)

  {

  echo "I is : $i <br />';

  }

  print_footer();

  其实你应该先在一个地方收集所有输出。你可以要么将它存储于函数中的变量内部,要么使用ob_start和ob_end_clean。所以,现在应该看起来像这样

  ?

  1

  2

  3

  4

  5

  6

  7

  8

  9

  10

  11

  12

  13

  14

  15

  16

  17

  18

  function print_header()

  {

  $o = "<p id='header'>Site Log and Login links</p>";

  return $o;

  }

  function print_footer()

  {

  $o = "<p id='footer'>Site was made by me</p>";

  return $o;

  }

  echo print_header();

  for($i = 0 ; $i < 100; $i++)

  {

  echo "I is : $i <br />';

  }

  echo print_footer();

  那么,为什么你应该做输出缓冲呢:

  你可以在将输出发送给浏览器之前更改它,如果你需要的话。例如做一些str_replaces,或者preg_replaces,又或者是在末尾添加一些额外的html,例如profiler/debugger输出。

  发送输出给浏览器,并在同一时间做php处理并不是好主意。你见过这样的网站,它有一个Fatal error在侧边栏或在屏幕中间的方框中吗?你知道为什么会出现这种情况吗?因为处理过程和输出被混合在了一起。

  8.当输出非HTML内容时,通过header发送正确的mime类型

  请看一些XML。

  ?

  1

  2

  3

  4

  5

  6

  7

  $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';

  $xml = "<response>

  <code>0</code>

  </response>";

  //Send xml data

  echo $xml;

  工作正常。但它需要一些改进。

  ?

  1

  2

  3

  4

  5

  6

  7

  8

  $xml = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>';

  $xml = "<response>

  <code>0</code>

  </response>";

  //Send xml data

  header("content-type: text/xml");

  echo $xml;

  请注意header行。这行代码告诉浏览器这个内容是XML内容。因此,浏览器能够正确地处理它。许多JavaScript库也都依赖于header信息。

  JavaScript,css,jpg图片,png图像也是一样:

  JavaScript

  ?

  1

  2

  3

  4

  5

  6

  header("content-type: application/x-javascript");

  echo "var a = 10";

  CSS

  header("content-type: text/css");

  echo "#p id { background:#000; }"

  9.为MySQL连接设置正确的字符编码

  曾碰到过unicode/utf-8字符被正确地存储在mysql表的问题,phpmyadmin也显示它们是正确的,但是当你使用的时候,你的网页上却并不能正确地显示。里面的奥妙在于MySQL连接校对。

  ?

  1

  2

  3

  4

  5

  6

  7

  8

  9

  10

  11

  12

  13

  14

  15

  16

  17

  18

  $host = 'localhost';

  $username = 'root';

  $password = 'super_secret';

  //Attempt to connect to database

  $c = mysqli_connect($host , $username, $password);

  //Check connection validity

  if (!$c)

  {

  die ("Could not connect to the database host: <br />". mysqli_connect_error());

  }

  //Set the character set of the connection

  if(!mysqli_set_charset ( $c , 'UTF8' ))

  {

  die('mysqli_set_charset() failed');

  }

  一旦你连接到数据库,不妨设置连接字符集。当你在你的应用程序中使用多种语言时,这绝对有必要。

  否则会发生什么呢?你会在非英文文本中看到很多的方框和????????。

  10.使用带有正确字符集选项的htmlentities

  PHP 5.4之前,使用的默认字符编码是ISO-8859-1,这不能显示例如? ? 这样的字符。

  ?

  1

  $value = htmlentities($this->value , ENT_QUOTES , 'UTF-8');

  从PHP 5.4起,默认编码成了UTF-8,这解决了大部分的问题,但你最好还是知道这件事,如果你的应用程序使用多种语言的话。

【对初学者非常有用的PHP技巧】相关文章:

PHP开发CS结构的技巧11-09

超级有用的PS技巧04-20

20条PHP代码优化技巧05-06

PHP中的Division by zero报错处理技巧02-23

php环境搭建06-11

PHP常量介绍04-21

PHP的基本作用03-17

PHP基本语法04-29

PHP变量介绍02-28

PHP语言发展历程08-29