Home Backend Development PHP Tutorial PHP 高手之路(一)_php基础

PHP 高手之路(一)_php基础

May 17, 2016 am 09:47 AM

PHP是一门高效的网络编程语言,由于它具有编写灵活、运行快速等优点,迅速成为Web程序员的首选语言。前不久的一份权威调查表明,现在已经有31.6%的网站使用PHP作为主要的服务器端编程语言。
  但是,要成为一名PHP编程高手却并不容易。并不像很多人想象的那样,只要能够飞快地编写几条简单的代码去解决一个复杂的问题就是PHP编程高手了,真正的PHP高手还需要考虑更多的其它问题。以下三条准则是一名成熟的PHP程序员在编程中应该首先遵循的准则。
  1.懒惰是金
  2.编写漂亮的代码
  3.追求程序的速度,而不是编程的速度
  一、懒惰是金
  做一个懒惰的程序员吗?这个想法太奇怪了!因为这个世界上最忙碌的人可能就是计算机程序员了。但正是因为程序员太忙了,所以才应该在编程时学会偷懒。
  对于一个程序员来说,懒惰的方法有两种:其一,大胆使用现成的别人的程序代码,把这些代码融入到你自己的程序或者项目中去。其二是编写一些有用的代码建立一个函数库,在将来编写程序时可以顺手拈来,省去了许多重复的劳动,自然就可以懒惰一点了。
  这两种偷懒的方法都非常适合PHP程序员了。
  首先,PHP是在自由开放的环境中诞生和成长的一门语言。在世界各地,有成千上万的程序员,他们一直在为PHP的完美而不断奋斗,他们也愿意和别人分享自己的聪明才智和自己编写的代码。你每天都可以从一些PHP网站、邮件列表、新闻组发现大量的优秀的程序代码。这样说,我并不是鼓励你整天等着让别人为你编写代码,但是你可以“站在伟人的肩膀上”,充分发扬“拿来主义”,聪明地应用别人的程序代码可以节省你大量时间。其次,在PHP中,你可以方便地建立自己的函数库,这样可以在你以后编写程序时省去很多麻烦。
  下面笔者为大家介绍几个通用的函数,这些函数有的来自网上的一些开放源代码的项目,有的精选自邮件列表。如果你能把它们加入到你自己的函数库中,迟早你将会发现自己受益无穷。
  1.通用数据库处理函数
  和其它的CGI函数相比,PHP的优点之一是具有很强大的数据库处理能力。但是,在PHP中,对于不同的数据库都使用一些特定的函数来专门处理,缺少通用的数据库处理函数。这大大降低了程序代码的可移植性,这也为初学编程的朋友带来了很多不便。
  在网上,许多程序员都通过封装类解决了这个问题。他们编写了统一的函数用来处理任何流行的数据库——不管是在Linux世界深受欢迎的Mysql还是在Windows平台上广泛流行的SqlServer。就笔者个人来说,非常喜欢使用这些函数,因为可以直接使用一些简单的诸如"query"、"next_record"之类的函数,而不需要考虑数据库的连接、数据库句柄这些复杂的东西,更不需要考虑使用的是何种数据库。
  如果你需要这些函数,你可以通过访问以下的几个网址而得到:
  http://phplib.netuse.de/
  http://phpclasses.UpperDesign.com/browse.html/package/20
  http://phpdb.linuxbox.com/
  2.变量调试函数
  PHP程序的调试一直是一件让人头疼的事,它既不像VB等高级语言那样有集成的编译调试环境,也不想Perl那样可以在Linux或者DOS环境下直接运行。其实,我们完全可以通过灵活地使用echo语句来完成对PHP的调试工作。
  下面的几个函数可以让你随时查看程序中任何变量的类型及其值。
  function ss_array_as_string (&$array, $column = 0) {
  $str = "Array(
n";
  while(list($var, $val) = each($array)){
  for ($i = 0; $i   $str .= "    ";
  }
  $str .= $var. ==> ;
  $str .= ss_as_string($val, $column+1)."
n";
  }
  for ($i = 0; $i   $str .= "    ";
  }
  return $str.);
  }
  function ss_object_as_string (&$object, $column = 0) {
   if (empty($object->classname)) {
  return "$object";
  }
  else {
  $str = $object->classname."(
n";
  while (list(,$var) = each($object->persistent_slots)) {
  for ($i = 0; $i   $str .= "    ";
  }
  global $$var;
  $str .= $var. ==> ;
  $str .= ss_as_string($$var, column+1)."
n";
  }
  for ($i = 0; $i   $str .= "    ";
  }
  return $str.);
  }
  }
  function ss_as_string (&$thing, $column = 0) {
  if (is_object($thing)) {
  return ss_object_as_string($thing, $column);
  }
  elseif (is_array($thing)) {
  return ss_array_as_string($thing, $column);
  }
  elseif (is_double($thing)) {
  return "Double(".$thing.")";
  }
  elseif (is_long($thing)) {
  return "Long(".$thing.")";
  }
  elseif (is_string($thing)) {
  return "String(".$thing.")";
  }
  else {
  return "Unknown(".$thing.")";
  }
  }
  需要的时候,在程序中简单地加入下面的一条代码即可查看程序中的所使用的变量(包括数组和对象)的类型和值:
  echo ss_as_string($my_variable);
  使用下面的语句,我们可以直接查看程序中所有的变量的值:
  echo ss_as_string($GLOBALS);
  3. 控制Log信息的函数
  调试PHP程序的另外一种重要的方法就是查看Log信息。如果能够方便地控制Log信息的级别以及Log信息的显示内容,将会给程序调试带来更多的便利。下面的几个函数可以方便地实现这个功能。
  $ss_log_level = 0;
  $ss_log_filename = /tmp/ss-log;
  $ss_log_levels = array(
  NONE => 0,
  ERROR => 1,
  INFO => 2,
  DEBUG => 3);
  function ss_log_set_level ($level = ERROR) {
  global $ss_log_level;
  $ss_log_level = $level;
  }
  function ss_log ($level, $message) {
  global $ss_log_level, $ss-log-filename;
  if ($ss_log_levels[$ss_log_level]   // 不显示Log信息
  return false;
  }
  $fd = fopen($ss_log_filename, "a+");
  fputs($fd, $level. - [.ss_timestamp_pretty().] - .$message."n");
  fclose($fd);
  return true;
  }
  function ss_log_reset () {
  global $ss_log_filename;
  @unlink($ss_log_filename);
  }
  在上面的函数中,有四个Log级别变量。运行PHP程序时,只有当Log的级别低于预设的级别值时,Log信息才可以被记录和显示出来。例如,在程序中加入如下的一条语句:
  ss_log_set_level(INFO);
  那么,运行PHP程序时,只有ERROR和INFO级别的LOG信息才能被记录和显示出来,DEBUG级的信息则被忽略了。除此之外,我们还可以设定显示的信息内容,其语句如下:
  ss_log(ERROR, "testing level ERROR");
  ss_log(INFO, "testing level INFO");
  ss_log(DEBUG, "testing level DEBUG");
  你也可以随时使用下面的语句清空LOG信息:
  ss_log_reset();
  4.速度测试函数

    为了优化代码,我们需要一种可以测试代码运行时间的方法,从而来选择最优的代码。下面的函数可以测试运行代码所需的时间:
  function ss_timing_start ($name = default) {
  global $ss_timing_start_times;
  $ss_timing_start_times[$name] = explode( , microtime());
  }
  function ss_timing_stop ($name = default) {
  global $ss_timing_stop_times;
  $ss_timing_stop_times[$name] = explode(, microtime());
  }
  function ss_timing_current ($name = default) {
  global $ss_timing_start_times, $ss_timing_stop_times;
  if (!isset($ss_timing_start_times[$name])) {
  return 0;
  }
  if (!isset($ss_timing_stop_times[$name])) {
  $stop_time = explode(, microtime());
  }
  else {
  $stop_time = $ss_timing_stop_times[$name];
  }
  $current = $stop_time[1] - $ss_timing_start_times[$name][1];
  $current += $stop_time[0] - $ss_timing_start_times[$name][0];
  return $current;
  }
  现在可以轻松地检查任何一段代码的执行时间了,甚至我们可以同时使用多个计时器,只需在使用上述的几个函数时设定不同的参数作为计时器的名称就可以了。
  5.调试和优化数据库的操作
  对于数据库来说,运行速度是至关重要的。尽管很多书籍和文章都讲授了一些快速运行数据库的方法,但是所有的方法都必须经过实践的检验。下面我们将把PHPLib函数库中的query()函数和上面介绍的几个函数综合起来编写成新的query()函数,和原先的函数相比,这个函数增加了运行时间的监测功能。
  function query($Query_String, $halt_on_error = 1) {
  $this->connect();
  ss_timing_start();
  $this->Query_ID = @mysql_query($Query_String,$this->Link_ID);
  ss_timing_stop();
  ss_log(INFO, ss_timing_current(). Secs - .$Query_String);
  $this->Row  = 0;
  $this->Errno = mysql_errno();
  $this->Error = mysql_error();
  if ($halt_on_error && !$this->Query_ID) {
  $this->halt("Invalid SQL: ".$Query_String);
  }
  return $this->Query_ID;
  }(未完待续)

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in Laravel Notifications in Laravel Mar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles