- 浏览: 103538 次
- 性别:
- 来自: 广州
-
文章分类
最新评论
-
zhangyulove911:
读XML in a Nutshell (10) -
sunzihao128858:
非常好
Red5源代码分析 - 关键类及其初始化过程 -
还是小鬼:
受用了
Red5源代码分析 - 关键类及其初始化过程 -
qiyue49:
如果有flex4版本,可以直接把C:\Program Fil ...
[转]Flex的中文编译 -
faylai:
标题党骗流量!
20090209-20090211 (about Red5 and Flex)
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
发表评论
-
20100723 (tc design)
2010-07-23 10:53 864What's "changablility" ... -
20091105 (logging)
2009-11-05 11:21 780log4j The inherited level for ... -
20091026 (Qaurtz)
2009-10-26 10:01 683The JobDetail object is created ... -
Stratus developer key
2009-07-01 14:14 0Your Stratus developer key is: ... -
thinking about pressure
2009-03-26 09:38 0之所以会对自己要求那 ... -
temp
2009-03-25 08:24 0http://cc.rtmfp.net/ -
20090320 (Spring integration)
2009-03-20 15:16 899Integrate with Struts: Spring p ... -
20090317-20090319 (struts)
2009-03-19 17:47 1098Conversion?Validation?How to bi ... -
20090319 (XWork)
2009-03-19 12:10 749ActionThe <action> tag ca ...
相关推荐
内容概要:本文详细介绍了基于MATLAB GUI界面和卷积神经网络(CNN)的模糊车牌识别系统。该系统旨在解决现实中车牌因模糊不清导致识别困难的问题。文中阐述了整个流程的关键步骤,包括图像的模糊还原、灰度化、阈值化、边缘检测、孔洞填充、形态学操作、滤波操作、车牌定位、字符分割以及最终的字符识别。通过使用维纳滤波或最小二乘法约束滤波进行模糊还原,再利用CNN的强大特征提取能力完成字符分类。此外,还特别强调了MATLAB GUI界面的设计,使得用户能直观便捷地操作整个系统。 适合人群:对图像处理和深度学习感兴趣的科研人员、高校学生及从事相关领域的工程师。 使用场景及目标:适用于交通管理、智能停车场等领域,用于提升车牌识别的准确性和效率,特别是在面对模糊车牌时的表现。 其他说明:文中提供了部分关键代码片段作为参考,并对实验结果进行了详细的分析,展示了系统在不同环境下的表现情况及其潜在的应用前景。
嵌入式八股文面试题库资料知识宝典-计算机专业试题.zip
嵌入式八股文面试题库资料知识宝典-C and C++ normal interview_3.zip
内容概要:本文深入探讨了一款额定功率为4kW的开关磁阻电机,详细介绍了其性能参数如额定功率、转速、效率、输出转矩和脉动率等。同时,文章还展示了利用RMxprt、Maxwell 2D和3D模型对该电机进行仿真的方法和技术,通过外电路分析进一步研究其电气性能和动态响应特性。最后,文章提供了基于RMxprt模型的MATLAB仿真代码示例,帮助读者理解电机的工作原理及其性能特点。 适合人群:从事电机设计、工业自动化领域的工程师和技术人员,尤其是对开关磁阻电机感兴趣的科研工作者。 使用场景及目标:适用于希望深入了解开关磁阻电机特性和建模技术的研究人员,在新产品开发或现有产品改进时作为参考资料。 其他说明:文中提供的代码示例仅用于演示目的,实际操作时需根据所用软件的具体情况进行适当修改。
少儿编程scratch项目源代码文件案例素材-剑客冲刺.zip
少儿编程scratch项目源代码文件案例素材-几何冲刺 转瞬即逝.zip
内容概要:本文详细介绍了基于PID控制器的四象限直流电机速度驱动控制系统仿真模型及其永磁直流电机(PMDC)转速控制模型。首先阐述了PID控制器的工作原理,即通过对系统误差的比例、积分和微分运算来调整电机的驱动信号,从而实现转速的精确控制。接着讨论了如何利用PID控制器使有刷PMDC电机在四个象限中精确跟踪参考速度,并展示了仿真模型在应对快速负载扰动时的有效性和稳定性。最后,提供了Simulink仿真模型和详细的Word模型说明文档,帮助读者理解和调整PID控制器参数,以达到最佳控制效果。 适合人群:从事电力电子与电机控制领域的研究人员和技术人员,尤其是对四象限直流电机速度驱动控制系统感兴趣的读者。 使用场景及目标:适用于需要深入了解和掌握四象限直流电机速度驱动控制系统设计与实现的研究人员和技术人员。目标是在实际项目中能够运用PID控制器实现电机转速的精确控制,并提高系统的稳定性和抗干扰能力。 其他说明:文中引用了多篇相关领域的权威文献,确保了理论依据的可靠性和实用性。此外,提供的Simulink模型和Word文档有助于读者更好地理解和实践所介绍的内容。
嵌入式八股文面试题库资料知识宝典-2013年海康威视校园招聘嵌入式开发笔试题.zip
少儿编程scratch项目源代码文件案例素材-驾驶通关.zip
小区开放对周边道路通行能力影响的研究.pdf
内容概要:本文探讨了冷链物流车辆路径优化问题,特别是如何通过NSGA-2遗传算法和软硬时间窗策略来实现高效、环保和高客户满意度的路径规划。文中介绍了冷链物流的特点及其重要性,提出了软时间窗概念,允许一定的配送时间弹性,同时考虑碳排放成本,以达到绿色物流的目的。此外,还讨论了如何将客户满意度作为路径优化的重要评价标准之一。最后,通过一段简化的Python代码展示了遗传算法的应用。 适合人群:从事物流管理、冷链物流运营的专业人士,以及对遗传算法和路径优化感兴趣的科研人员和技术开发者。 使用场景及目标:适用于冷链物流企业,旨在优化配送路线,降低运营成本,减少碳排放,提升客户满意度。目标是帮助企业实现绿色、高效的物流配送系统。 其他说明:文中提供的代码仅为示意,实际应用需根据具体情况调整参数设置和模型构建。
少儿编程scratch项目源代码文件案例素材-恐怖矿井.zip
内容概要:本文详细介绍了基于STM32F030的无刷电机控制方案,重点在于高压FOC(磁场定向控制)技术和滑膜无感FOC的应用。该方案实现了过载、过欠压、堵转等多种保护机制,并提供了完整的源码、原理图和PCB设计。文中展示了关键代码片段,如滑膜观测器和电流环处理,以及保护机制的具体实现方法。此外,还提到了方案的移植要点和实际测试效果,确保系统的稳定性和高效性。 适合人群:嵌入式系统开发者、电机控制系统工程师、硬件工程师。 使用场景及目标:适用于需要高性能无刷电机控制的应用场景,如工业自动化设备、无人机、电动工具等。目标是提供一种成熟的、经过验证的无刷电机控制方案,帮助开发者快速实现并优化电机控制性能。 其他说明:提供的资料包括详细的原理图、PCB设计文件、源码及测试视频,方便开发者进行学习和应用。
基于有限体积法Godunov格式的管道泄漏检测模型研究.pdf
嵌入式八股文面试题库资料知识宝典-CC++笔试题-深圳有为(2019.2.28)1.zip
少儿编程scratch项目源代码文件案例素材-几何冲刺 V1.5.zip
Android系统开发_Linux内核配置_USB-HID设备模拟_通过root权限将Android设备转换为全功能USB键盘的项目实现_该项目需要内核支持configFS文件系统
C# WPF - LiveCharts Project
少儿编程scratch项目源代码文件案例素材-恐怖叉子 动画.zip
嵌入式八股文面试题库资料知识宝典-嵌⼊式⼯程师⾯试⾼频问题.zip