[Zend PHP5 Cerification] Lectures -- 10. Supplementary

A. PHP hasa large collection of built in functions to handle strings, we’velooked at strings already, let’s look at different ways to interactwith them in greater detail:

 

strlen(), Returnsthe length of the string passed to it:

echo strlen('Jello');//5
$a = array("Hello World", "a");
echostrlen($a); //5

str_replace() & strtr()
Searches thegiven string for the needle, replacing it with the presentedstring:

echo str_replace("a", "b", "abc");//bbc
echo str_replace(array('a','b','c'), array('b','c','a'),'abc'); //aaa
echo strtr('abc','ab','bc'); //bcc

strcmp() &strcasecmp()

These functions compare two strings, returningzero when they match, greater than one when string 1 > string 2,and less than one when string 1 < string 2:

echostrcmp('hello', 'Hello'); // > 1
echo strcasecmp('hello','Hello'); // 0


strpos() & strstr()
strpos willreturn the position of the search string within the target. strstrwill return the portion of target from the beginning of the firstmatch until the end. Both function have case
insensitivecounterparts:

echo strpos('hello new world', 'new'); //6
echostrstr('hello new world', 'new'); //new world


strspn() &strcspn()
Apply a mask to a given string, strspn() returns thenumber of characters matching the mask, strcspn() uses a blacklistand returns the number of non-matching characters:

$mask ="abcdefg ";
$string = "beg bad fed billy";//strlen($string) = 17
echo strspn($string, $mask); //13
$mask= "abcdefg";
$string = "joy to the world";//strlen($string) = 16
echo strcspn($string, $mask); //9

substr()– Used to retrieve a portion of a string

$string = "Iam the very model of the modern major
general";
echosubstr($string, 2);
//am the very model of the modern majorgeneral
echo substr($string, 9, 10); //very model
echosubstr($string, -7); //general
echo substr($string, 5, -8);
//thevery model of the modern major

If start is non-negative, thereturned string will start at the start'th position in string,counting from zero. For instance, in the string 'abcdef', thecharacter at position 0 is 'a', the character at position 2 is 'c',and so forth.
If start is negative, the returned string will startat the start'th character from the end of string.

If string isless than or equal to start characters long, FALSE will bereturned.

If length is given and is positive, the stringreturned will contain at most length characters beginning from start(depending on the length of string).
If length is given and isnegative, then that many characters will be omitted from the end ofstring (after the start position has been calculated when a start isnegative). If start denotes a position beyond this truncation, anempty string will be returned.

 

Complex (curly)syntax

This isn't calledcomplex because the syntax is complex, but because you can includecomplex expressions this way.

In fact, you caninclude any value that is in the namespace in strings with thissyntax. You simply write the expression the same way as you wouldoutside the string, and then include it in { and }. Since you can'tescape '{', this syntax will only be recognised when the $ isimmediately following the {. (Use "{\$" to get a literal"{$").

 

 

 

Which syntax ispreferred in PHP5? $a[0] or $a{0}

The {} syntax isdepreciated in PHP 6.

 

 

strlen(null); //0

 

 

 

B: I listed someextra questions I found during I took the phparch’s Vulcan Zend PHP5 Certification Testings. This post listed some EASIER but will notbe frequently asked in the actual exam I think. But, they are worthynoted here, they can also serve as check points for you previouslylearned knowledge.

 

Youcan determine if you can seek an arbitrary stream in PHP with thestream_get_meta_data()function

The$params[’notification’]context variable allows you todefine a callback for the stream that will notify your script ofcertain events during the course of the transaction.

ThePDOStatement->nextRowset()method in the PDOStatement class is used to return the next resultset in a multi-query statement.

SimpleXMLobjects can be created from what types of datasources?
File
URL
String

Duringan HTTP authentication, how does one determine the username andpassword provided by the browser?
predefinedvariables PHP_AUTH_USER, PHP_AUTH_PW, and AUTH_TYPE set to the username, password and authentication type respectively. These predefinedvariables are found in the $_SERVER and $HTTP_SERVER_VARSarrays.
$_SERVER[’PHP_AUTH_USER’]
$_SERVER[’PHP_AUTH_PW’]

End ascript in PHP5:
__halt_compiler();
die();
exit();

Whenchecking to see if two variables contain the same instance of anobject, which of the following comparisons should be used?
===

Whenan object is serialized, which method will be called, automatically,providing your object with an opportunity to close any resources orotherwise prepare to be serialized?
serialize— Generates a storable representation of a value.
Whenserializing objects, PHP will attempt to call the member function__sleep() prior to serialization. This is to allow the object to doany last minute clean-up, etc. prior to being serialized. Likewise,when the object is restored using unserialize() the __wakeup() memberfunction is called.

Whichof the following are examples of the new engine executor modelsavailable in PHP 5?
Threeexecution models (CALL, GOTO, SWITCH) that the new virtual machine ofPHP 5.1
Switch
Conditional
Goto
Call
Dynamic

Thearray_sum()function is used to add up the values of every entry within an array.

Thechildren()method can be used from a SimpleXML node to return an iteratorcontaining a list of all of the current node’s sub nodes.

Todestroy one variable within a PHP session you should use which methodin PHP 5?
session_destroy();session_regenerate_id();

Unlikea database such as MySQL, SQLite columns are not explicitly typed.Instead, SQLite catagorizes data into which of the followingcatagories?
Textual andNumeric

Whichtwo internal PHP interfaces provide functionality which allow you totreat an object like an array?
Iterator
ArrayAccess

Thestream_set_timeout()function is used to modify the amount of time PHP will wait for astream before timing out during reading or writing.

In ageneral sense, which is more important: performance ormaintainability of an application?
maintainabilityfirst, performance second.

Whenusing a function such as strip_tags, are markup-based attacks stillpossible?
yes.
stringstrip_tags ( string $str [, string $allowable_tags ] )
Whichof the following are valid PHP variables?

@$foo
//&$variable
${0×0}
$variable
//$0×0

Unlikethe old MySQL extension, the new MySQLi extension requires that youprovide what when performing a query when using the proceduralinterface?
Proceduralstyle:
mixedmysqli_query ( mysqli $link , string $query [, int $resultmode ] )

AFOREIGN key is particularly useful for maintaining data integritywithin your database, and has the potential to ease the complexity ofyour PHP scripts by allowing the database to manage cascading deletesof data.
If you would liketo store your session in the database, you would do which of thefollowing?

Createfunctions for each session handling step and usesession_set_save_handler() to override PHP’s internal settings

Onecan determine if it is possible to send HTTP headers from within yourPHP script using which of the following functions?
boolheaders_sent ([ string &$file [, int &$line ]] )

Checkto make sure we haven’t already sent
theheader:

!in_array(”Location:$url”, headers_list())

Thetempnam function is used to generate a file resource in the filesystem with a randomly-generated filename to be used as temporarystorage
stringtempnam ( string $dir , string $prefix )
Createsa file with a unique filename, with access permission set to 0600, inthe specified directory. If the directory does not exist, tempnam()may generate a file in the system’s temporary directory, and returnthe name of that.

C:Here listed someWEIRD and STRANGE questions I found in the phparch’s simulatorexam. You may think these are some advanced features of the PHP5language, but some of them are actually mention in the GUIDE also.However, some of the questions, I found that there maybe some errorsin the question itself; in this case, I marked with the “*” infront of the question. Therefore, some of the answer I gave maybe notright, or maybe I get the meaning of the questions wrong. So, if youhave any comment on this post, please feel free to tell me.

*What three special methods can be used to perform special logic inthe event a particular accessed method or member variable is notfound?

__get($name)

__set($set,$val)

 

 

__call($method,$args)

 

 

__get()and __set() are called when accessing or assigning an undefinedobject property, while __call() is executed when calling anon-existent method of a class.

 

 

*When writing portable database code using PDO, what is thePDO::ATTR_CASE attribute useful for?

Forcecolumn names to a specific case specified by the PDO::CASE_*constants.

 

 

XPath

<?php

$dom= new DomDocument();

$dom->load('test.xml');

$xpath= new DomXPath($dom);

DOMXPath->query()— Evaluates the given XPath expression

$nodes= $xpath->query(???????, $dom->documentElement);

echo$nodes->item(0)->getAttributeNode('bgcolor')->value

."\n";

?>

http://www.w3schools.com/xpath/xpath_syntax.asp

 

 

 

 

 

 

 

 

*Whatshould go in the ??????? assignment below to create a Zlib-compressedfile foo.gz with a compression level of 9?

 

 

<?php

 

 

$file= '????????';

 

 

$fr= fopen($file, 'wb9');

fwrite($fr,$data);

fclose($fr);

 

 

?>

*Whatshould be replaced in the string ??????? below to open the archivemyarchive.gz located in the document root of the www.example.comserver and decompress it?

 

 

<?php

 

 

$file= '???????';

 

 

$fr= fopen($file, 'rb');

 

 

$data= "";

while(!feof($fr)){

$data.= fgets($fr, 1024);

}

 

 

fclose($fr);

 

 

?>

compress.zlib://

 

 

*Inthe event of a PDOException, $info is set with the contents of the$errorInfo property of the exception

anarray of error information about the last operation performed by thisdatabase handle. The array consists of the following fields:

ElementInformation

0SQLSTATE error code (a five-character alphanumeric identifierdefined in the ANSI SQL standard).

1Driver-specific error code.

2Driver-specific error message.

 

 

 

 

 

 

*Indatabases that do not support the AUTO_INCREMENT modifier, you mustuse a LAST_INSERT_ID(id+1) instead to auto-generate a numericincrementing key.

 

 

 

 

 

 

*Arefollowing incorrect? Only two are wrong, not four.

a. function c(MyClass $a = new MyClass())

b. function d($a = null)

c. function e(&$a = 30)

d. function a(&$a = array(10,20,30))

e. function b($a = (10 + 2))

 

 

 

 

 

 

*Howdoes one create a cookie which will exist only until the browsersession is terminated?

boolsetcookie ( string $name [, string $value [, int $expire [, string$path [, string $domain [, bool $secure [, bool $httponly ]]]]]] )

If$expire set to 0, or omitted, the cookie will expire at the end ofthe session (when the browser closes).

 

 

*Ifregular expressions must be used, in general which type of regularexpression functions available to PHP is preferred for performancereasons?

 

 

PHP’sRegular Expression Functions (POSIX Extended). regex

POSIX

eregfunctions

Perl-style

pregfunctions.

Perl-compatiblesyntax using the PCRE functions. These functions support non-greedymatching, assertions, conditional subpatterns, and a number of otherfeatures not supported by the POSIX-extended regular expressionsyntax.This extension maintains a global per-thread cache of compiledregular expressions (up to 4096).

 

 

 

 

 

 

*Whichof the following extensions are no longer part of PHP 5 and have beenmoved to PECL?

w32api,PDF, ICONV

 

 

*Namethree new extensions in PHP 5

SimpleXML,PDO, tidy, MySQLi, sqlite, soap

 

 

(hash,Reflection,libxml2-basedDOM and XSL extensions DOMXML)

 

 

 

 

 

 

*Whichof the following SQL statements will improve SQLite writeperformance?

PRAGMAlocking_mode = "Row";

PRAGMAcount_changes = Off;

PRAGMAdefault_synchronous = Off;

PRAGMAdefault_synchronous = On;

PRAGMAlocking_mode = "Table";

 

 

*Whatkind of information is acquired when profiling a PHP script?

timer,functions executed

 

 

*Themethod used to create a new node to be added into an XML documentusing DOM is the DOMDocument->createElement() method

 

 

 

 

<?php

functionfunc(&$arraykey) {

return$arraykey; // function returns by value!

}

 

 

$array= array('a', 'b', 'c');

foreach(array_keys($array) as $key) {

$y= &func($array[$key]);

$z[]=& $y;

}

 

 

var_dump($z);

?>

//compare to $z[] = ['c', 'c', 'c'];

 

 

*Implementingyour own PDO class requires which steps from the list below?

extendingPDO;

extendingPDOStatement;

PDO->setAttribute(PDO::ATTR_STATEMENT_CLASS=>array(stringclassname, array(mixed constructor_args))

 

 

*The implode() function is used to convert an array into a string,maintaining your ability to return the string into an array

Whichof the following functions allow you to introspect the call stackduring execution of a PHP script?

 

 

arraydebug_backtrace ( void ), generates a PHP backtrace.

posted @ 2010-06-29 17:30  DavidHHuan  阅读(557)  评论(0编辑  收藏  举报