20100712 (php study)

String:
 With single-quoted strings, the only special characters you need to escape inside a string are backslash and the single quote itself.Because PHP doesn’t check for variable interpolation or almost any escape sequences in single-quoted strings, defining strings this way is straightforward and fast.
 Double-quoted strings don’t recognize escaped single quotes, but they do recognize interpolated variables and the escape sequences.
 Heredoc -specified strings recognize all the interpolations and escapes of double-quoted strings, but they don’t require double quotes to be escaped. Heredocs start with <<< and a token. That token (with no leading or trailing whitespace), followed by semicolon a to end the statement (if necessary), ends the heredoc.
 Individual bytes in strings can be referenced with square brackets. You can also use curly braces to access individual byte in a string. That is, $neighbor{3} is the same as $neighbor[3]. The curly brace syntax is a newer addition to PHP. It provides a visual distinction between string indexing and array indexing.
 Interpolation with double-quoted strings places some limitations on the syntax of what can be interpolated. In the previous example, $amounts['payment'] had to be written as $amounts[payment] so it would be interpolated properly. Use curly braces around more complicated expressions to interpolate them into a string.
 
 
Array:
 $fruits[] = 'Dates'; Assigning a value to an array with an empty subscript is shorthand for adding a new element to the end of the array.
 To define an array using not integer keys but string keys, you can also use array( ), but specify the key/value pairs with =>.
 Instead of creating a numeric array with string values, you can create an associative array and place your values as its keys. If you want, you can then store additional information in the element’s value. There’s no speed penalty for doing this, and PHP preserves the ordering.
 for ($key = 0, $size = count($array); $key < $size; $key++)
 foreach ($fruits as $fruit)
 foreach ($fruits as $color => $fruit)
 You want to assign multiple elements to an array in one step, but you don’t want the first index to be 0.
 $whig_presidents = array(9 => 'Harrison', 'Tyler',* 12 => 'Taylor', 'Fillmore');
 $fruits['red'][] = 'strawberry';
 If you’re unsure if the data you’ll be processing is a scalar or an array, you need to protect against calling foreach with a non-array. One method is to use is_array( ):
  if (is_array($items)) {// foreach loop code for array
  } else {// code for scalar
  }
 Another method is to coerce all variables into array form using settype( ):
 settype($items, 'array'); // loop code for arrays
 To delete one element, use unset( ):
  unset($array[3]);
  unset($array['foo']);
 To delete multiple noncontiguous elements, also use unset( ):
  unset($array[3], $array[5]); 
  unset($array['foo'], $array['bar']);
 To delete multiple contiguous elements, use array_splice( ):
  array_splice($array, $offset, $length);
 If you unset( ) an element, PHP adjusts the array so that looping still works correctly. It doesn’t compact the array to fill in the missing holes. This is what we mean when we say that all arrays are associative, even when they appear to be numeric.
 
 
Variable:
 The function isset( ) returns true when passed a variable that’s set. To turn a variable that’s set into one that’s unset, call unset( ) on the variable or assign null to the variable.
 All unset variables are also empty. Set variables may be empty or nonempty. Empty variables have values that evaluate to false as a boolean: the integer 0, the double 0.0, the empty string, the string "0", the boolean false, an array with no elements, an object with no properties (in versions of PHP prior to PHP 5) and NULL. Everything else is nonempty. This includes the string "00", and the string " ", containing just a space character.
 Constants and return values from functions can be false, but they can’t be empty.
 if (empty($first_name)) { .. } if (empty(0)) { .. } if (empty(get_first_name())) { .. }
 if ($dwarves = 12) { ... }  // $dwarves = 12 evaluates to 12, which is true.
 if (12 = $dwarves) { ... }  // so use this
 Putting a constant on the left side of a comparison coerces the comparison to the type of the constant.
 PHP’s list( ) language construct lets you assign values from an array to individual variables.
 To swap $a and $b: list($a,$b) = array($b,$a);
 Placing two dollar signs before a variable name causes PHP to de-reference the right variable name to get a value.
 $animal = 'turtles'; $turtles = 103; print $$animal;
 PHP evaluates the expression between the curly braces and uses it as a variable name.
 ${'stooge_'.strtolower($s)}
 The curly brace syntax is also necessary in resolving ambiguity about array elements.
 $$donkeys[12] ${$donkeys[12]} ${$donkeys}[12]
 Declaring a variable static causes its value to be remembered by a function. So, if there are subsequent calls to the function, you can access the value of the saved variable.
 While static variables retain their values between function calls, they do so only during one invocation of a script. A static variable accessed in one request doesn’t keep its value for the next request to the same page.
 Use serialize( ) to encode variables and their values into a textual form.
 To recreate the variables, use unserialize( ).
 You want to inspect the values stored in a variable. It may be a complicated nested array or object, so you can’t just print it out or loop through it. Use print_r( ) or var_dump( ).

 
Function:
 Unless specified, all non-object values being passed into and out of a function are passed by value, not by reference. (By default, objects are passed by reference.)
 Assign the default value to the parameters inside the function prototype: function wrap_html_tag($string, $tag = 'b') { }
 To instruct a function to accept an argument passed by reference instead of value, prepend an & to the parameter name in the function prototype: function wrap_html_tag(&$string, $tag = 'b') { }
 First, func_num_args( ) returns an integer with the number of arguments passed into its invoking function.
 From there, you can then call func_get_arg( ) to find the specific argument value for each position.
 There is a third version of this function that uses func_get_args( ) to return an array containing all the values passed to the function.
 The syntax for returning a variable by reference is similar to passing it by reference. However, instead of placing an & before the parameter, place it before the name of the function:
 function &pc_array_find_value($needle, &$haystack) {}
 Also, you must use the =& assignment operator instead of plain = when invoking the function:
 $html =& pc_array_find_value('The Doors', $artists);
 You want to return more than one value from a function. Return an array and use list( ) to separate elements:
 function averages($stats) { return array($median, $mean, $mode); }
 list($median, $mean, $mode) = averages($stats);
 A function returns multiple values, but you only care about some of them. Omit variables inside of list( ):
 list(, $minute,) = time_parts('12:34:56');
 You want to call different functions depending on a variable’s value. Use call_user_func( ):
 call_user_func($function, $filename);
 Use call_user_func_array( ) when your functions accept differing argument counts:
 call_user_func_array($function, $args);
 You need to access a global variable inside a function.
 Bring the global variable into local scope with the global keyword:
 global $chew_count;
 global $age,$gender,shoe_size;
 Or reference it directly in $GLOBALS:
 $i = $GLOBALS['chew_count'];
 Declaring a variable global inside a function is similar to assigning a reference of the global variable to the local one:
 $food = &GLOBALS['food'];
 So if you call unset( ) on a variable brought into local scope using the global keyword, the variable is unset only within the function. To unset the variable in the global scope, you must call unset( ) on the element of the $GLOBALS array.
 You want to create and define a function as your program is running. Use create_function( ):
 $add = create_function('$i,$j', 'return $i+$j;');
 
 
Class and Object:
 Be careful not to mistakenly type $this->$size. This is legal, but it’s not the same as $this->size. Instead, it accesses the property of the object whose name is the value stored in the $size variable.
 Besides using -> to access a method or member variable, you can also use :: . This syntax accesses static methods in a class.
 You want to define a method that is called when an object is instantiated. Define a method named __construct( ).
 To make PHP call a method when an object is eliminated, define a method named __destruct( ).
 You want to prevent another developer from redefining specific methods within a child class, or even from subclassing the entire class itself.
 final public function connect($server, $username, $password) { }
 final class MySQL { }
 You want to control how PHP displays an object when you print it. Implement a __toString( ) method.
 Your __toString( ) method must return a string; otherwise, PHP will issue an error. If you suspect you may be in a position to return a non-string value from this method, consider explicitly casting the results.
 return (string) $this->label;
 To check if a class implements a specific interface, use class_implements( )
 class Book implements Nameable {}
 $interfaces = class_implements('Book');
 if (isset($interfaces['Nameable'])) { }
 You can also use the Reflection classes
 class Book implements Nameable { }
 $rc = new ReflectionClass('Book');
 if ($rc->implementsInterface('Nameable')) { }
 You want to create an “abstract” class, or, in other words, one that is not directly instantiable, but acts as a common base for children classes.
 Do this by placing the abstract keyword before the class definition.
 abstract class Database { }
 You must also define at least one abstract method in your class. Do this by placing the abstract keyword in front of the method definition:
 abstract public function connect();
 Copy objects by reference using =:
 $rasmus = $zeev;
 Copy objects by value using clone:
 $rasmus = clone $zeev; 
 Control how PHP 5 clones an object by implementing a __clone( ) method in your class. When this method exists, PHP allows __clone( ) to override its default behavior
 class Person {
  // ... everything from before
  public function __clone() {
   $this->address = clone $this->address;
  }
 }
 Inside of __clone( ), you’re automatically presented with a shallow copy of the variable, stored in $this , the object that PHP provides when __clone( ) does not exist.
 Use the magical methods __get( ) and __set( ) to intercept property requests.
 To improve this abstraction, also implement __isset( ) and __unset( ) methods to make the class behave correctly when you check a property using isset( ) or delete it using unset( ).
 There are three downsides to using __get( ) and __set( ). First, these methods only catch missing properties. If you define a property for your class, __get( ) and __set( ) are not invoked by PHP when that property is accessed.
 Second, these methods completely destroy any notion of property inheritance. If a parent object has a __get( ) method and you implement your own version of __get( ) in the child, your object won’t function correctly because the parent’s __get( ) method is never called.
 Other reasons to consider not using magical accessors are:
 They’re relatively slow. They’re both slower than direct property access and explicitly writing accessor methods for all your properties.
 They make it impossible for the Reflection classes and tools such as phpDocumentor to automatically document your code.
 You cannot use them with static properties.
 Aggregate the objects together and use the __call( ) magic method to intercept method invocations and route them accordingly. When you invoke methods not defined in a class, the __call( ) method catches them and, when applicable, you can dispatches them using call_user_func_array( ).
 public function __call($method, $arguments) {
  if (method_exists($this->address, $method)) {
   return call_user_func_array(array($this->address, $method), $arguments);
  }
 }
 You want to access a method in the parent class that’s been overridden in the child. Prefix parent:: to the method name.
 You want to define constants on a per-class basis, not on a global basis.
 Define them like class properties, but use the const label instead. Unlike properties, constants do not have a dollar sign ($) before them.
 class Circle {
  const pi = 3.14159;
  protected $radius;
  public function circumference() {
   return 2 * self::pi * $this->radius;
  }
 }
 $area = Circle::pi * $radius * $radius;
 You want to control how an object behaves when you serialize( ) and unserialize( ) it. This is useful when you need to establish and close connections to remote resources, such as databases, files, and web services. Define the magical methods __sleep( ) and __wakeUp( ).
 Use the Reflection classes to probe an object for information.
 For a quick overview of the class, call Reflection::export( ):
 // learn about cars
 Reflection::export(new ReflectionClass('car'));
 Or probe for specific data:
 $car = new ReflectionClass('car');
 if ($car->hasMethod('retractTop')) {
  // car is a convertible
 }
 To check that a value passed as a function argument is an instance of a specific class,
 specify the class name in your function prototype:
 public function add(Person $person) {
  // add $person to address book
 }
 In other contexts, use the instanceof operator:
 <?php
  $media = get_something_from_catalog();
  if ($media instanceof Book) {
   // do bookish things
  } else if ($media instanceof DVD) {
   // watch the movie
  }
 ?>
 One way of enforcing controls on your objects is by using type hints. A type hint is a way to tell PHP that an object passed to a function or method must be of a certain class. To do this, specify a class name in your function and method prototypes. As of PHP 5.1, you can also require that an argument is an array, by using the keyword array. This only works for classes and arrays, though, not for any other variable types. You cannot, for example, specify strings or integers.
 You don’t want to include all your class definitions within every page. Instead, you want to dynamically load only the ones necessary in that page. Use the __autoload( ) magic method:
 function __autoload($class_name) {
  include "$class_name.php";
 }
 $person = new Person;
 You want to instantiate an object, but you don’t know the name of the class until your code is executed. For example, you want to localize your site by creating an object belonging to a specific language. However, until the page is requested, you don’t know which language to select. Use a variable for your class name:
 $language = $_REQUEST['language'];
 $valid_langs = array('en_US' => 'US English',
  'en_UK' => 'British English',
  'es_US' => 'US Spanish',
  'fr_CA' => 'Canadian French');
 if (isset($valid_langs[$language]) && class_exists($language)) {
  $lang = new $language;
 }
 
 
Web:
 You want direct access to the body of a post request, not just the parsed data that PHP puts in $_POST for you. For example, you want to handle an XML document that’s been posted as part of a web services request. Read from the php://input stream:
 <?php
  $body = file_get_contents('php://input');
 ?>
 You want to start generating output before you’re finished sending headers or cookies. Call ob_start( ) at the top of your page and ob_end_flush( ) at the bottom. You can then intermix commands that generate output and commands that send headers. The output won’t be sent until ob_end_flush( ) is called.
 You can pass ob_start( ) the name of a callback function to process the output buffer with that function. This is useful for postprocessing all the content in a page, such as hiding email addresses from address-harvesting robots.
 The output_buffering configuration directive turns output buffering on for all pages:
 output_buffering = On
 Similarly, output_handler sets an output buffer processing callback to be used on all pages:
 output_handler=mangle_email
 Setting an output_handler automatically sets output_buffering to on
 You want to send compressed content to browsers that support automatic decompression. Add this setting to your php.ini file:
 zlib.output_compression=1
 You can adjust the compression level with the zlib.output_compression_level configuration directive:
 ; minimal compression
 zlib.output_compression_level=1
 ; maximal compression
 zlib.output_compression_level=9
 At higher compression levels, less data needs to be sent from the server to the browser, but more server CPU time must be used to compress the data.
 You want to get the value of an environment variable. Read the value from the $_ENV auto-global array.
 <?php
  $name = $_ENV['USER'];
 ?>
 The $_ENV array is created only if the value of the variables_order configuration directive contains E. If $_ENV isn’t available, use getenv( ) to retrieve an environment variable.
 <?php
  $path = getenv('PATH');
 ?>
 To set an environment variable in a script, use putenv( ).
 <?php
  putenv('ORACLE_SID=ORACLE'); // configure oci extension
 ?>
 To set an environment variable in your Apache httpd.conf file, use SetEnv. Note that variables set this way show up in the PHP auto-global array $_SERVER, not $_ENV.
 <?php
  SetEnv DATABASE_PASSWORD password
 ?>

 
Form:
 These are then directly accessible in the following arrays: $_GET, $_POST, $_FILES, $_COOKIE, $_SERVER, and $_ENV. They hold, respectively, all variables set in the query string, in the body of a
post request, by uploaded files, by cookies, by the web server, and by the environment in which the web server is running. There’s also $_REQUEST, which is one giant array that contains the values from the other six arrays. When placing elements inside of $_REQUEST, if two arrays both have a key with the same name, PHP breaks the tie by relying on the variables_order configuration directive.
 Use the $_SERVER['REQUEST_METHOD'] variable to determine whether the request was submitted with the get or post method.
 One other technique also makes pages easier to maintain: don’t hardcode the path to your page directly into the form action. This makes it impossible to rename or relocate your page without also editing it. Instead, use the $_SERVER['SCRIPT_NAME'] variable as the form action. This is set up by PHP on each request to contain the filename (relative to the document root) of the current script.
 You want to securely display user-entered data on an HTML page. For example, you want to allow users to add comments to a blog post without worrying that HTML or JavaScript in a comment will cause problems. Pass user input through htmlentities( ) before displaying it.
 <?php
  print 'The comment was: ';
  print htmlentities($_POST['comment']);
 ?>
 You want to process a file uploaded by a user. For example, you’re building a photosharing web site and you want to store user-supplied photos. Use the $_FILES array to get information about uploaded files.
 name The name of the uploaded file. This is supplied by the browser so it could be a full pathname or just a filename.
 type The MIME type of the file, as supplied by the browser.
 size The size of the file in bytes, as calculated by the server.
 tmp_name The location in which the file is temporarily stored on the server.
 error An error code describing what (if anything) went wrong with the file upload. (This element is available in PHP 4.2.0 and later versions.)
 The possible values of the error element are:
 UPLOAD_ERR_OK (0) Upload succeeded (no error).
 UPLOAD_ERR_INI_SIZE (1) The size of the uploaded file is bigger than the value of the upload_max_filesize configuration directive.
 UPLOAD_ERR_FORM_SIZE (2) The size of the uploaded file is bigger than the value of the form’s MAX_FILE_SIZE element.
 UPLOAD_ERR_PARTIAL (3) Only part of the file was uploaded.
 UPLOAD_ERR_NO_FILE (4) There was no file uploaded.
 UPLOAD_ERR_NO_TMP_DIR (6) The upload failed because there was no temporary directory to store the file (available in PHP 4.3.10, 5.0.3, and later).
 UPLOAD_ERR_CANT_WRITE (7) PHP couldn’t write the file to disk (available in PHP 5.1.0 and later).
 You have form elements that let a user select multiple choices, such as a drop-down menu or a group of checkboxes, but PHP sees only one of the submitted values. End the form element’s name with a pair of square brackets ([]):
 <input type="checkbox" name="boroughs[]" value="bronx"> The Bronx
 <input type="checkbox" name="boroughs[]" value="brooklyn"> Brooklyn
 <input type="checkbox" name="boroughs[]" value="manhattan"> Manhattan
 <input type="checkbox" name="boroughs[]" value="queens"> Queens
 <input type="checkbox" name="boroughs[]" value="statenisland"> Staten Island
 A similar syntax also works with multidimensional arrays. For example, you can have a checkbox such as <input type="checkbox" name="population[NY][NYC]" value="8008278">. If checked, this form element sets $_POST['population']['NY'] ['NYC'] to 8008278.
 
Database:
 You want access to a SQL database to store or retrieve information. Without a database, dynamic web sites aren’t very dynamic. Create a new PDO object with the appropriate connection string.
 $mysql = new PDO('mysql:host=db.example.com;port=31075;dbname=food', $user, $password)
 Note that to use a particular PDO backend, PHP must be built with support for that backend. Use the output from phpinfo( ) to determine what PDO backends your PHP setup has.
 You want to retrieve some data from your database. Use PDO::query( ) to send the SQL query to the database, and then a foreach loop to retrieve each row of the result, as shown in Example 10-9.
 <?php
  $st = $db->query('SELECT symbol,planet FROM zodiac');
  foreach ($st->fetchAll() as $row) {
   print "{$row['symbol']} goes with {$row['planet']} <br/>\n";
  }
 ?>
 The query( ) method returns a PDOStatement object. Its fetchAll( ) provides a concise way to do something with each row returned from a query.
 The fetch( ) method returns a row at a time. Each call to fetch( ) returns the next row in the result set. When there are no more rows available, fetch( ) returns false. By default, fetch( ) returns an array containing each column in the result set row twice — once with an index corresponding to the column name and once with a numerical index.
 You want to add, remove, or change data in an SQL database. Use PDO::exec( ) to send an INSERT, DELETE, or UPDATE command.
 $db->exec("INSERT INTO family (id,name) VALUES (1,'Vito')");
 You can also prepare a query with PDO::prepare( ) and execute it with PDOStatement::execute( ).
 $st = $db->prepare('INSERT INTO family (id,name) VALUES (?,?)');
 $st->execute(array(1,'Vito'));
 You want to run the same query multiple times, substituting in different values each time. Set up the query with PDO::prepare( ) and then run it by calling execute( ) on the prepared statement that prepare( ) returns. The placeholders in the query passed to prepare( ) are replaced with data by execute( ).
 <?php
  // Prepare
  $st = $db->prepare("SELECT sign FROM zodiac WHERE element LIKE ?");
  // Execute once
  $st->execute(array('fire'));
  while ($row = $st->fetch()) {
   print $row[0] . "<br/>\n";
  }
  // Execute again
  $st->execute(array('water'));
  while ($row = $st->fetch()) {
   print $row[0] . "<br/>\n";
  }
 ?>
 In addition to the ? placeholder style, PDO also supports named placeholders. If you’ve got a lot of placeholders in a query, this can make them easier to read. Instead of ?, put a placeholder name (which has to begin with a colon) in the query, and then use those placeholder names (without the colons) as keys in the parameter array you pass to execute( ).
 $st = $db->prepare(
 "SELECT sign FROM zodiac WHERE element LIKE :element OR planet LIKE :planet");
 // SELECT sign FROM zodiac WHERE element LIKE 'earth' OR planet LIKE 'Mars'
 $st->execute(array('planet' => 'Mars', 'element' => 'earth'));
 $row = $st->fetch();
 If you’re issuing an INSERT, UPDATE, or DELETE with PDO::exec( ), the return value from exec( ) is the number of modified rows. If you’re issuing an INSERT, UPDATE, or DELETE with PDO::prepare( ) and PDOStatement::execute( ), call PDOStatement::rowCount( ) to get the number of modified rows.
 If you’re issuing a SELECT statement, the only foolproof way to find out how many rows are returned is to retrieve them all with fetchAll( ) and then count how many rows you have.
 If you need to apply escaping yourself, use the PDO::quote( ) method. The PDO::quote( ) method makes sure that text or binary data is appropriately quoted, but you may also need to quote the SQL wildcard characters % and _ to ensure that SELECT statements using the LIKE operator return the right results.
 Use PDO::errorCode( ) or PDOStatement::errorCode( ) after an operation to get an error code if the operation failed. The corresponding errorInfo( ) method returns more information about the error.
 The errorCode( ) method returns a five-character error code. PDO uses the SQL 92 SQLSTATE error codes. By that standard, 00000 means “no error,” so a call to errorCode( ) that returns 00000 indicates success. The errorInfo( ) method returns a three-element array. The first element contains the five-character SQLSTATE code (the same thing that errorCode( ) returns). The second element is a database backend-specific error code. The third element is a database backend-specific error message.
 To have PDO throw exceptions every time it encounters an error, call setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION) on your PDO object after it’s created. This way, you can handle database problems uniformly instead of larding your code with repeated calls to errorCode( ) and errorInfo( ).
 Similar to the exception error mode is the “warning” error mode. setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING) tells PDO to issue warnings when a database error is encountered. If you prefer to work with regular PHP errors instead of exceptions, this is the error mode for you. Set up a custom error handler with set_error_handler( ) to handle E_WARNING level events and you can deal with your database problems in the error handler.
 Use PHP’s uniqid( ) function to generate an identifier. To restrict the set of characters in the identifier, pass it through md5( ), which returns a string containing only numerals and the letters a through f.
 <?php
  $st = $db->prepare('INSERT INTO users (id, name) VALUES (?,?)');
  $st->execute(array(uniqid(), 'Jacob'));
  $st->execute(array(md5(uniqid()), 'Ruby'));
 ?>
 When the database creates ID values automatically, the PDO::lastInsertId( ) method retrieves them. Call lastInsertId( ) on your PDO object to get the auto-generated ID of the last inserted row.
 
Session:
 Use the sessions module. The session_start( ) function initializes a session, and accessing an element in the auto-global $_SESSION array tells PHP to keep track of the corresponding variable:
 <?php
  session_start();
  $_SESSION['visits']++;
  print 'You have visited here '.$_SESSION['visits'].' times.';
 ?>
 To start a session automatically on each request, set session.auto_start to 1 in php.ini. With session.auto_start, there’s no need to call session_start( ).
 With the session.use_trans_sid configuration directive turned on, if PHP detects that a user doesn’t accept the session ID cookie, it automatically adds the session ID to URLs and forms.
 
 
Other:
 You want to get the value of a PHP configuration setting. Use ini_get( ):
 $include_path = ini_get('include_path');
 To get all the configuration variable values in one step, call ini_get_all( ). It returns the variables in an associative array, and each array element is itself an associative array. The second array has three elements: a global value for the setting, a local value, and an access code.
 You want to change the value of a PHP configuration setting. Use ini_set( ):
 ini_set('include_path', ini_get('include_path') . ':/home/fezzik/php');
 Configuration variables are not permanently changed by ini_set( ). The new value lasts only for the duration of the request in which ini_set( ) is called. To make a persistent modification, alter the values stored in the php.ini file.
 To reset a variable back to its original setting, use ini_restore( ):
 ini_restore('sendmail_from'); // go back to the default value
 You don’t want PHP error messages visible to users. Set the following values in your php.ini or web server configuration file:
 display_errors =off
 log_errors =on
 When log_errors is set to on, error messages are written to the server’s error log. If you want PHP errors to be written to a separate file, set the error_log configuration directive with the name of that file:
 error_log = /var/log/php.error.log
 You want to alter the error-logging sensitivity on a particular page. This lets you control what types of errors are reported. To adjust the types of errors PHP complains about, use error_reporting( ):
 error_reporting(E_ALL); // everything
 error_reporting(E_ERROR | E_PARSE); // only major problems
 error_reporting(E_ALL & ~E_NOTICE); // everything but notices
 PHP 5 introduced a new error level, E_STRICT. Enabling E_STRICT during development has the benefit of PHP alerting you of ways your code could be improved. You will receive warnings about the use of deprecated functions, along with tips to nudge you in the direction of the latest and greatest suggested methods of coding. E_STRICT is the only error level not included in E_ALL; for maximum coverage during development, set the error reporting level to E_ALL | E_STRICT.
 You want to create a custom error handler that lets you control how PHP reports errors. To set up your own error function, use set_error_handler( ):
 set_error_handler('pc_error_handler');
 function pc_error_handler($errno, $error, $file, $line) {
  $message = "[ERROR][$errno][$error][$file:$line]";
  error_log($message);
 }
 You want to save program errors to a log. These errors can include everything from parser errors and files not being found to bad database queries and dropped connections. Use error_log( ) to write to the error log:
 if (ldap_errno($ldap)) {
  error_log("LDAP Error #" . ldap_errno($ldap) . ": " . ldap_error($ldap));
 }
 When you include a file with blank lines outside <?php ?> tags, the blank lines are sent to the browser. Use trim( ) to remove leading and trailing blank lines from files. If you don’t want to worry about blank lines disrupting the sending of headers, turn on output buffering.
 You want to make debugging easier by adding statements to print out variables. But you want to be able to switch back and forth easily between production and debug modes.
 Put a function that conditionally prints out messages based on a defined constant in a page included using the auto_prepend_file configuration setting. Save the following code to debug.php:
 // turn debugging on
 define('DEBUG',true);
 // generic debugging function
 function pc_debug($message) {
  if (defined('DEBUG') && DEBUG) {
   error_log($message);
  }
 }
 Set the auto_prepend_file directive in php.ini or your site .htaccess file: auto_prepend_file=debug.php 

你可能感兴趣的:(sql,mysql,PHP,SQL Server,Access)