PHP面试题(English)

1. What is the difference between == and === in PHP?

The == operator just checks to see if the left and right values are equal. But, the === operator (note the extra “=”) actually checks to see if the left and right values are equal, and also checks to see if they are of the same variable type (like whether they are both booleans, ints, etc.).

//good code:

if ( strpos( $inputString, 'xyz' ) === false ) {        

    // do something

 }

2.How would you parse HTML in PHP?

1) Get HTML elments

// Create DOM from URL or file

$html = file_get_html('http://www.google.com/');

// Find all images

foreach($html->find('img') as $element)

       echo $element->src . '<br>';

// Find all links

foreach($html->find('a') as $element)

       echo $element->href . '<br>'; 

2) modify HTML elements

// Create DOM from string

$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');



$html->find('div', 1)->class = 'bar';



$html->find('div[id=hello]', 0)->innertext = 'foo';



echo $html; // Output: <div id="hello">foo</div><div id="world" class="bar">World</div>

3) extract contents from HTML

// Dump contents (without tags) from HTML

echo file_get_html('http://www.google.com/')->plaintext; 

4) scraping slashdot

// Create DOM from URL

$html = file_get_html('http://slashdot.org/');



// Find all article blocks

foreach($html->find('div.article') as $article) {

    $item['title']     = $article->find('div.title', 0)->plaintext;

    $item['intro']    = $article->find('div.intro', 0)->plaintext;

    $item['details'] = $article->find('div.details', 0)->plaintext;

    $articles[] = $item;

}



print_r($articles); 

3. In PHP, what are magic methods and how are they used?

PHP functions that start with a double underscore – a “__” – are called magic functions (and/or methods) in PHP. They are functions that are always defined inside classes, and are not stand-alone (outside of classes) functions. The magic functions available in PHP are: __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state(), __clone(), and __autoload().

The most commonly used magic function is __construct(). This is because as of PHP version 5, the __construct method is basically the constructor for your class. If PHP 5 can not find the __construct() function for a given class, then it will search for a function with the same name as the class name – this is the old way of writing constructors in PHP, where you would just define a function with the same name as the class.

Now, here is an example of a class with the __construct() magic function:

class Animal {



public $height;      // height of animal  

public $weight;     // weight of animal



public function __construct($height, $weight) 

{

 $this->height = $height;  //set the height instance variable

 $this->weight = $weight; //set the weight instance variable

}

}

4.in PHP, what is the difference between self and $this?

$this is used to reference the current object, whereas self is used to access the current class itself.

class Animal {

     public function whichClass() {

        echo "I am an Animal!";

    }

   /*  Note that this method uses the $this keyword  so

       the calling object's class type (Tiger) will be 

       recognized and the Tiger class version of the

       whichClass method will be called.

   */

    public function sayClassName() {

       $this->whichClass();

    }

}



class Tiger extends Animal {

    public function whichClass() {

        echo "I am a Tiger!";

    }

}



$tigerObj = new Tiger();

$tigerObj->sayClassName();

5.In PHP, what is the difference between self and static?

6.How would you find out if a string contains another string in PHP?

if (strpos($aString,'Waldo') !== false) {

    echo 'I found Waldo!';

}

7. How to delete an element from an array in php?

$anArray = array("X", "Y", "Z");

unset($anArray[0]);

//'dumps' the content of $anArray to the page:

var_dump($anArray);  

This would output the following:

array(4) { [0]=> string(1) "V" [1]=> string(1) "W" [3]=> string(1) "Y" [4]=> string(1) "Z" }

Using array_splice to delete an element from an array

The array_splice function is used to take one part of an array and replace it with some other contents. It can also be used to delete an element in an array. Here is an example and explanation of how to use array_splice to delete an element:

$anArray = array("V", "W", "X", "Y", "Z");

/*The 2 represents the offset - which basically means move 2 positions from the  beginning of the

array and that will take us to the "X" element.  The 1 represents the length of the array that you want to 

delete.  Since we just want to delete 1 element, we set the length parameter to 1.
And, since we are not replacing that element with anything - we do just want to delete it - we leave the 4th parameter ( which is optional) blank
*/ array_splice($anArray, 2, 1); var_dump($anArray);

7.How would you convert a PHP variable to a string? Is there something like the toString method that Java has in PHP?

PHP has casting operators that can be used to convert non-string variables into strings.

// this is an integer:

$nonStringVar = 123;

/*now $stringVar is a string because  the "(string)" performs a type ast and returns the string equivalent of the integer */

$stringVar = (string)$nonStringVar;

You can also use the function strval to get the string value of a variable.

// this is an integer:

$nonStringVar = 123;

//now $stringVar is a string

$aString = strval($nonStringVar);

8.What is the best way to return data in the JSON format from PHP?

If you are running PHP 5.2 or greater, you can use the built-in json_encode function to return JSON formatted data from PHP. Here is an example of it’s usage:

$tennisArray = array('Djokovic' => 1, 'Federer' => 2, 'Nadal' => 3, 'Murray' => 4);

echo json_encode($tennisArray);

If you are running a version of PHP that came before 5.2 then you can use the PHP extension called PECL available here: JSON and PHP

9. How would you return an array from a function in PHP?

function someFunc( ) {

$aVariable = 10;

$aVariable2 = 20;

return array($aVariable, $aVariable2);

}

10.How do you delete cookies in PHP? Also, provide an example showing how it’s done.

The setcookie() function can actually accept up to six arguments, but only one argument is actually required — and that is the cookie name. If you use the setcookie function, and just pass a cookie name without a value, then it will have the same effect as deleting the existing cookie with the same exact name. For example, to create a cookie called first_name, you use this line:

   setcookie('first_name', 'Robert'); 

Example of deleting a cookie in PHP:

setcookie('first_name');   

But, as an extra safety measure, you should also set the expiration time to a time in the past – as you can see below where we pass in “time() – 300″ for the expiration date. This is the way we recommend that you delete the cookie in PHP:

Recommended way to delete a cookie in PHP:

setcookie('first_name', '', time()-300);   

11.What’s the difference between a cookie and a session in PHP?

PHP sessions improve upon cookies because they allow web applications to store and retrieve more information than cookies. PHP sessions actually use cookies, but they add more functionality and security.

Sessions store data on the server, not on the browser like cookies

 

The main difference between a session and a cookie is that session data is stored on the server, whereas cookies store data in the visitor’s browser. Sessions use a session identifier to locate a particular user’s session data. This session identifier is normally stored in the user’s web browser in a cookie, but the sensitive data that needs to be more secure — like the user’s ID, name, etc. — will always stay on the server.

 

Sessions are more secure than cookies

 

So, why exactly should we use sessions when cookies work just fine? Well, as we already mentioned, sessions are more secure because the relevant information is stored on the server and not sent back and forth between the client and server. The second reason is that some users either turn off cookies or reject them. In that scenario, sessions, while designed to work with a cookie, can actually work without cookies as a workaround, as you can read about here: Can PHP sessions work without cookies?.

 

Sessions need extra space, unlike cookies

PHP sessions, unlike cookies which are just stored on the user’s browser, need a temporary directory on the server where PHP can store the session data.

Sessions must use the session_start function

A very important thing to remember when using sessions is that each page that will use a session must begin by calling the session_start() function. The session_start() function tells PHP to either start a brand new session or access an existing one.

Registering values to the session

After the session_start function is called, values can be registered to the session using the $_SESSION associative array. This is what it would look like:

   $_SESSION['name'] = 'Jack';

   $_SESSION['last_name'] = 'Lopez';   

 

你可能感兴趣的:(english)