php零基礎到就業直播視訊課:進入學習
程式設計師必備介面測試偵錯工具:
話題: PHP
困難: ⭐
==
則在兩個不同的型別之間進行強制轉換===
操作符執行’型別安全比較‘這意味著只有當兩個運算元具有相同的型別和相同的值時,它才會返回 TRUE。
1 === 1: true 1 == 1: true 1 === "1": false // 1 是一個整數, "1" 是一個字串 1 == "1": true // "1" 強制轉換為整數,即1 "foo" === "foo": true // 這兩個運算元都是字串,並且具有相同的值
? 源自: stackoverflow.com
話題: PHP
困難: ⭐
為了能夠通過參照傳遞變數,我們在其前面使用 &,如下所示:
$var1 = &$var2
? 源自: guru99.com
話題: PHP
困難: ⭐
$GLOBALS
是關聯陣列,包含對指令碼全域性範圍內當前定義的所有變數的參照。
? 源自: guru99.com
話題: PHP
困難: ⭐
PHP 允許使用者使用 ini_set () 修改 php.ini 中提到的一些設定。此函數需要兩個字串引數。第一個是要修改的設定的名稱,第二個是要分配給它的新值。
給定的程式碼行將啟用指令碼的 display_error 設定 (如果它被禁用)。
ini_set('display_errors', '1');
我們需要將上面的語句放在指令碼的頂部,以便該設定一直保持啟用狀態,直到最後。此外,通過 ini_set () 設定的值僅適用於當前指令碼。此後,PHP 將開始使用 php.ini 中的原始值。
? 源自: github.com/Bootsity
話題: PHP
困難: ⭐⭐
require()
函數與 include()
函數相同,只是它處理錯誤的方式不同。如果出現錯誤,include()
函數會生成警告,但指令碼會繼續執行。require()
函數會產生致命錯誤,指令碼會停止。
我的建議是 99.9% 的時間裡只使用 require_once
。
使用 require
或 include
代替意味著您的程式碼在其他地方不可重用,即您引入的指令碼實際上是在執行程式碼,而不是提供類或某些類功能庫。
? Source: stackoverflow.com
主題: PHP
難度: ⭐⭐
stdClass
只是將其他型別強制轉換為物件時使用的通用」 空’’類。stdClass
不是 PHP 中物件的基礎類別。這可以很容易地證明:
class Foo{} $foo = new Foo(); echo ($foo instanceof stdClass)?'Y':'N'; // 輸出'N'
對於匿名物件,動態屬性等很有用。
考慮 StdClass
的一種簡單使用場景是替代關聯陣列。請參見下面的範例,該範例顯示 json_decode()
如何允許獲取 StdClass 範例或關聯陣列。
同樣但未在本範例中顯示的 SoapClient::__soapCall
返回一個 StdClass
範例。
//帶有StdClass的範例 $json = '{ "foo": "bar", "number": 42 }'; $stdInstance = json_decode($json); echo $stdInstance - > foo.PHP_EOL; //"bar" echo $stdInstance - > number.PHP_EOL; //42 //Example with associative array $array = json_decode($json, true); echo $array['foo'].PHP_EOL; //"bar" echo $array['number'].PHP_EOL; //42
? 源自: stackoverflow.com
話題: PHP
困難: ⭐⭐
沒有區別,它們是一樣的。 選擇 die()
而不是 exit()
的唯一好處可能是你節省了額外來鍵入一個字母的時間.
? 源自: stackoverflow.com
話題: PHP
困難: ⭐⭐
const
和 define
的根本區別在於,const
在編譯時定義常數,而 define
在執行時定義常數。
const FOO = 'BAR'; define('FOO', 'BAR'); // but if (...) { const FOO = 'BAR'; // 無效 } if (...) { define('FOO', 'BAR'); // 有效 }
同樣在 PHP 5.3 之前,const
命令不能在全域性範圍內使用。你只能在類中使用它。當你想要設定與該類相關的某種常數選項或設定時,應使用此選項。或者你可能想要建立某種列舉。一個好的 const
用法的例子是擺脫了魔術數位。
Define
可以用於相同的目的,但只能在全域性範圍內使用。它應該僅用於影響整個應用程式的全域性設定。
除非你需要任何型別的條件或表示式定義,否則請使用 consts
而不是 define()
—— 這僅僅是為了可讀性!
? 源自: stackoverflow.com
話題: PHP
困難: ⭐⭐
array_key_exists
它會告訴你陣列中是否存在鍵,並在 $a
不存在時報錯。null
,isset
才會返回 true
。當 $a
不存在時,isset
不會報錯。考慮:
$a = array('key1' => 'Foo Bar', 'key2' => null); isset($a['key1']); // true array_key_exists('key1', $a); // true isset($a['key2']); // false array_key_exists('key2', $a); // true
? 源自: stackoverflow.com
話題: PHP
困難: ⭐⭐
var_dump
函數用於顯示變數 / 表示式的結構化資訊,包括變數型別和變數值。陣列遞迴瀏覽,縮排值以顯示結構。它還顯示哪些陣列值和物件屬性是參照。
print_r()
函數以我們可讀的方式顯示有關變數的資訊。陣列值將以鍵和元素的格式顯示。類似的符號用於物件。
考慮:
$obj = (object) array('qualitypoint', 'technologies', 'India');
var_dump($obj)
將在螢幕的輸出下方顯示:
object(stdClass)#1 (3) { [0]=> string(12) "qualitypoint" [1]=> string(12) "technologies" [2]=> string(5) "India" }
stdClass Object ( [0] => qualitypoint [1] => technologies [2] => India )
? 源自: stackoverflow.com
話題: PHP
困難: ⭐⭐
notice
不是一個嚴重的錯誤,它說明執行過程中出現了一些錯誤,一些次要的錯誤,比如一個未定義的變數。warning
。 這個錯誤和上面的錯誤發生,指令碼都將繼續。fatal error
致命錯誤將終止程式碼。未能滿足 require () 將生成這種型別的錯誤。? 源自: pangara.com
話題: PHP
困難: ⭐⭐
檢查 php.ini 中的 「display_errors
」 是否等於 「on」,或者在指令碼中宣告 「ini_set('display_error',1)
」。
然後,在你的程式碼中包含 「ERROR_REPORTING(E_ALL)
」,以便在指令碼執行期間顯示所有型別的錯誤訊息。
? 源自: codementor.io
話題: PHP
困難: ⭐⭐
思考:
function showMessage($hello = false){ echo ($hello) ? 'hello' : 'bye'; }
? 源自: codementor.io
話題: PHP
困難: ⭐⭐
PHP 只支援單一繼承;這意味著使用關鍵字’extended’只能從一個類擴充套件一個類。
? 源自: guru99.com
話題: PHP
困難: ⭐⭐
在 PHP 中,通過值傳遞的物件。
? 源自: guru99.com
話題: PHP
困難: ⭐⭐
!=
表示 不等於 (如果 $a 不等於 $b,則為 True), !==
表示 不全等 (如果 $a 與 $b 不相同,則為 True).
? 源自: guru99.com
話題: PHP
困難: ⭐⭐
PDO 代表 PHP 資料物件。
它是一組 PHP 擴充套件,提供核心 PDO 類和資料庫、特定驅動程式。它提供了供應商中立、輕量級的資料存取抽象層。因此,無論我們使用哪種資料庫,發出查詢和獲取資料的功能都是相同的。它側重於資料存取抽象,而不是資料庫抽象。
? 源自: github.com/Bootsity
Topic: PHP
Difficulty: ⭐⭐
當程式執行出現異常報錯時,後面的程式碼將不會再執行,這時 PHP 將會嘗試匹配第一個 catch 塊進行異常的處理,如果沒有捕捉到異常程式將會報致命錯誤並顯示」Uncaught Exception」。
可以在 PHP 中丟擲和捕獲異常。
為了處理異常,程式碼可以被包圍在」try」 塊中.
每個 try 必須至少有一個對應的 catch
塊 。多個不同的 catch 塊可用於捕獲不同類的異常。
在 catch 塊中也可以丟擲異常(或重新丟擲之前的異常)。
思考:
try { print "this is our try block n"; throw new Exception(); } catch (Exception $e) { print "something went wrong, caught yah! n"; } finally { print "this part is always executed n"; }
? Source: github.com/Bootsity
Topic: PHP
Difficulty: ⭐⭐
echo
和 print
基本上是一樣的。他們都是用來列印輸出資料的。
區別在於:
? Source: github.com/Bootsity
Topic: PHP
Difficulty: ⭐⭐⭐
require_once()
作用與 require()
的作用是一樣的,都是參照或包含外部的一個 php 檔案,require_once()
引入檔案時會檢查檔案是否已包含,如果已包含,不再包含 (require) 它。
我建議在 99.9% 的時候要使用 require_once
使用 require
或 include
意味著您的程式碼不可在其他地方重用,即您要拉入的指令碼實際上是在執行程式碼,而不是提供類或某些函數庫。
? Source: stackoverflow.com
Topic: PHP
Difficulty: ⭐⭐⭐
思考:
function has_string_keys(array $array) { return count(array_filter(array_keys($array), 'is_string')) > 0; }
如果 $array
至少有一個字串型別的 key ,它將被視為關聯陣列。
? Source: stackoverflow.com
Topic: PHP
Difficulty: ⭐⭐⭐
這裡有幾種實現方法:
思考 get-data.php:
echo json_encode(42);
思考 index.html:
<script> function reqListener () { console.log(this.responseText); } var oReq = new XMLHttpRequest(); // new 一個請求物件 oReq.onload = function() { // 在這裡你可以操作響應資料 // 真實的資料來自 this.responseText alert(this.responseText); // 將提示: 42 }; oReq.open("get", "get-data.php", true); // ^ 不要阻塞的其餘部分執行。 // 不要等到請求結束再繼續。 oReq.send(); </script>
<div id="dom-target" style="display: none;"> <?php $output = "42"; // 此外, 做一些操作,獲得 output. echo htmlspecialchars($output); /* 你必須避免特殊字元,不然結果將是無效HTML。 */ ?> </div> <script> var div = document.getElementById("dom-target"); var myData = div.textContent; </script>
<script> var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; // Don't forget the extra semicolon! </script>
? Source: stackoverflow.com
Topic: PHP
Difficulty: ⭐⭐⭐
PHP 陣列通過複製進行賦值,而物件通過參照進行賦值。所有預設情況下,PHP 將複製這個陣列。這裡有一個 PHP 參考,一目瞭然:
$a = array(1,2); $b = $a; // $b 是一個不同的陣列 $c = &$a; // $c 是 $a 的參照
? Source: stackoverflow.com
Topic: PHP
Difficulty: ⭐⭐⭐
Consider the code:
$a = new stdClass(); $a->foo = "bar"; $b = clone $a; var_dump($a === $b);
What will be echoed to the console?
Two instances of the same class with equivalent members do NOT match the ===
operator. So the answer is:
bool(false)
? Source: stackoverflow.com
Topic: PHP
Difficulty: ⭐⭐⭐
Consider the code. What will be returned as a result?
$something = 0; echo ('password123' == $something) ? 'true' : 'false';
The answer is true
. You should never use ==
for string comparison. Even if you are comparing strings to strings, PHP will implicitly cast them to floats and do a numerical comparison if they appear numerical. ===
is OK.
For example
'1e3' == '1000' // true
also returns true.
? Source: stackoverflow.com
Topic: PHP
Difficulty: ⭐⭐⭐
array_walk
takes an array and a function F and modifies it by replacing every element x with F(x).array_map
does the exact same thing except that instead of modifying in-place it will return a new array with the transformed elements.array_filter
with function F, instead of transforming the elements, will remove any elements for which F(x) is not true? Source: stackoverflow.com
Topic: PHP
Difficulty: ⭐⭐⭐
exec()
is for calling a system command, and perhaps dealing with the output yourself.system()
is for executing a system command and immediately displaying the output - presumably text.passthru()
is for executing a system command which you wish the raw return from - presumably something binary.? Source: stackoverflow.com
Topic: PHP
Difficulty: ⭐⭐⭐
/** * Singleton class * */ final class UserFactory { /** * Call this method to get singleton * * @return UserFactory */ public static function Instance() { static $inst = null; if ($inst === null) { $inst = new UserFactory(); } return $inst; } /** * Private ctor so nobody else can instantiate it * */ private function __construct() { } }
To use:
$fact = UserFactory::Instance(); $fact2 = UserFactory::Instance();
But:
$fact = new UserFactory()
Throws an error.
? Source: stackoverflow.com
Topic: PHP
Difficulty: ⭐⭐⭐
query
runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.execute
runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute will also perform better if you are repeating a query multiple times.Best practice is to stick with prepared statements and execute for increased security. Aside from the escaping on the client-side that it provides, a prepared statement is compiled on the server-side once, and then can be passed different parameters at each execution.
? Source: stackoverflow.com
Topic: PHP
Difficulty: ⭐⭐⭐
Null coalescing operator returns its first operand if it exists and is not NULL. Otherwise it returns its second operand.
Example:
$name = $firstName ?? $username ?? $placeholder ?? "Guest";
? Source: github.com/Bootsity
Topic: PHP
Difficulty: ⭐⭐⭐
Error
is not possible. The only solution to errors is to terminate the execution. Where as you can recover from Exception
by using either try-catch blocks or throwing exception back to caller.Errors
using try-catch blocks. Even if you handle them using try-catch blocks, your application will not recover if they happen. On the other hand, Exceptions
can be handled using try-catch blocks and can make program flow normal if they happen.Exceptions
are related to application where as Errors
are related to environment in which application is running.? Source: github.com/Bootsity
Topic: PHP
Difficulty: ⭐⭐⭐
There are following functions which can be used from Exception
class.
getMessage()
− message of exceptiongetCode()
− code of exceptiongetFile()
− source filenamegetLine()
− source linegetTrace()
− n array of the backtrace()
getTraceAsString()
− formated string of traceException::__toString
gives the string representation of the exception.? Source: github.com/Bootsity
Topic: PHP
Difficulty: ⭐⭐⭐
call by value: (here we pass the value directly )
call by reference: (here we pass the address location where the value is stored)
? Source: github.com/Bootsity
Topic: PHP
Difficulty: ⭐⭐⭐
In case of call by reference, actual value is modified if it is modified inside the function. In such case, we need to use &
symbol with formal arguments. The &
represents reference of the variable.
Example:
function adder(&$str2) { $str2 .= 'Call By Reference'; } $str = 'This is '; adder($str); echo $str;
Output:
This is Call By Reference
? Source: github.com/Bootsity
Topic: PHP
Difficulty: ⭐⭐⭐
The extract()
function imports variables into the local symbol table from an array.
This function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table.
This function returns the number of variables extracted on success.
Example:
$a = "Original"; $my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse"); extract($my_array); echo "\$a = $a; \$b = $b; \$c = $c";
Output:
$a = Cat; $b = Dog; $c = Horse
? Source: github.com/Bootsity
Topic: PHP
Difficulty: ⭐⭐⭐⭐
Consider this code:
public function getTotal($tax) { $total = 0.00; $callback = function ($quantity, $product) use ($tax, &$total) { $pricePerItem = constant(__CLASS__ . "::PRICE_" . strtoupper($product)); $total += ($pricePerItem * $quantity) * ($tax + 1.0); }; array_walk($this->products, $callback); return round($total, 2); }
Could you explain why use it?
This is how PHP expresses a closure. Basically what this means is that you are allowing the anonymous function to 「capture」 local variables (in this case, $tax
and a reference to $total
) outside of it scope and preserve their values (or in the case of $total the reference to $total itself) as state within the anonymous function itself.
A closure is a separate namespace, normally, you can not access variables defined outside of this namespace.
use
allows you to access (use) the succeeding variables inside the closure.use
is early binding. That means the variable values are COPIED upon DEFINING the closure. So modifying $tax inside the closure has no external effect, unless it is a pointer, like an object is.&$total
. This way, modifying the value of $total
DOES HAVE an external effect, the original variable’s value changes.? Source: stackoverflow.com
Topic: PHP
Difficulty: ⭐⭐⭐⭐
Basically, it boils down to the fact that the self
keyword does not follow the same rules of inheritance. self
always resolves to the class in which it is used. This means that if you make a method in a parent class and call it from a child class, self
will not reference the child as you might expect.
Late static binding introduces a new use for the static
keyword, which addresses this particular shortcoming. When you use static
, it represents the class where you first use it, ie. it ‘binds’ to the runtime class.
Consider:
class Car { public static function run() { return static::getName(); } private static function getName() { return 'Car'; } } class Toyota extends Car { public static function getName() { return 'Toyota'; } } echo Car::run(); // Output: Car echo Toyota::run(); // Output: Toyota
? Source: stackoverflow.com
Topic: PHP
Difficulty: ⭐⭐⭐⭐
I want to know how many milliseconds a PHP while-loop takes to execute. Could you help me?
You can use the microtime
function for this.
Consider:
$start = microtime(true); while (...) { } $time_elapsed_secs = microtime(true) - $start;
? Source: stackoverflow.com
Topic: PHP
Difficulty: ⭐⭐⭐⭐
//We have this: $objectA->a; $objectA->b; $objectB->c; $objectB->d; //We want the easiest way to get: $objectC->a; $objectC->b; $objectC->c; $objectC->d;
This works:
$obj_merged = (object) array_merge((array) $obj1, (array) $obj2);
You may also use array_merge_recursive
to have a deep copy behavior.
One more way to do that is:
foreach($objectA as $k => $v) $objectB->$k = $v;
This is faster than the first answer in PHP versions < 7 (estimated 50% faster). But in PHP >= 7 the first answer is something like 400% faster.
? Source: stackoverflow.com
Topic: PHP
Difficulty: ⭐⭐⭐⭐
Let’s name some:
PDO is the standard, it’s what most developers will expect to use.
Moving an application from one database to another isn’t very common, but sooner or later you may find yourself working on another project using a different RDBMS. If you’re at home with PDO then there will at least be one thing less to learn at that point.
A really nice thing with PDO is you can fetch the data, injecting it automatically in an object.
PDO has some features that help agains SQL injection
In sense of speed of execution MySQLi wins, but unless you have a good wrapper using MySQLi, its functions dealing with prepared statements are awful. inserts - almost equal, selects - mysqli is2.5% faster for non-prepared statements/6.7% faster for prepared statements.
? Source: stackoverflow.com
Topic: PHP
Difficulty: ⭐⭐⭐⭐
This <=>
operator will offer combined comparison in that it will:
Consider:
//Comparing Integers echo 1 <= > 1; //outputs 0 echo 3 <= > 4; //outputs -1 echo 4 <= > 3; //outputs 1 //String Comparison echo "x" <= > "x"; // 0 echo "x" <= > "y"; //-1 echo "y" <= > "x"; //1
? Source: github.com/Bootsity
Topic: PHP
Difficulty: ⭐⭐⭐⭐
Standard php does not provide any multithreading but there is an (experimental) extension that actually does - pthreads
. The next best thing would be to simply have one script execute another via CLI, but that’s a bit rudimentary. Depending on what you are trying to do and how complex it is, this may or may not be an option.
? Source: github.com/Bootsity
Topic: PHP
Difficulty: ⭐⭐⭐⭐
PHP is not single threaded by nature. It is, however, the case that the most common installation of PHP on unix systems is a single threaded setup, as is the most common Apache installation, and nginx doesn’t have a thread based architecture whatever. In the most common Windows setup and some more advanced unix setups, PHP can and does operate multiple interpreter threads in one process.
PHP as an interpreter had support for multi-threading since the year 2000.
? Source: github.com/Bootsity
Topic: PHP
Difficulty: ⭐⭐⭐⭐⭐
It’s known you can’t put two __construct functions with unique argument signatures in a PHP class but I’d like to do something like this:
class Student { protected $id; protected $name; // etc. public function __construct($id){ $this->id = $id; // other members are still uninitialised } public function __construct($row_from_database){ $this->id = $row_from_database->id; $this->name = $row_from_database->name; // etc. } }
What is the best way to achieve this in PHP?
I’d probably do something like this:
class Student { public function __construct() { // allocate your stuff } public static function withID( $id ) { $instance = new self(); $instance->loadByID( $id ); return $instance; } public static function withRow( array $row ) { $instance = new self(); $instance->fill( $row ); return $instance; } protected function loadByID( $id ) { // do query $row = my_awesome_db_access_stuff( $id ); $this->fill( $row ); } protected function fill( array $row ) { // fill all properties from array } }
Then if i want a Student where i know the ID:
$student = Student::withID( $id );
Technically you’re not building multiple constructors, just static helper methods, but you get to avoid a lot of spaghetti code in the constructor this way.
Another way is to use the mix of factory and fluent style:
class Student { protected $firstName; protected $lastName; // etc. /** * Constructor */ public function __construct() { // allocate your stuff } /** * Static constructor / factory */ public static function create() { $instance = new self(); return $instance; } /** * FirstName setter - fluent style */ public function setFirstName( $firstName) { $this->firstName = $firstName; return $this; } /** * LastName setter - fluent style */ public function setLastName( $lastName) { $this->lastName = $lastName; return $this; } } // create instance $student= Student::create()->setFirstName("John")->setLastName("Doe");
? Source: stackoverflow.com
Topic: PHP
Difficulty: ⭐⭐⭐⭐⭐
You cannot overload PHP functions. Function signatures are based only on their names and do not include argument lists, so you cannot have two functions with the same name.
You can, however, declare a variadic function that takes in a variable number of arguments. You would use func_num_args()
and func_get_arg()
to get the arguments passed, and use them normally.
Consider:
function myFunc() { for ($i = 0; $i < func_num_args(); $i++) { printf("Argument %d: %s\n", $i, func_get_arg($i)); } } /* Argument 0: a Argument 1: 2 Argument 2: 3.5 */ myFunc('a', 2, 3.5);
? Source: github.com/Bootsity
為了處理異常,程式碼可能被包圍在一個 try
塊中。
每個 try 必須至少有一個提示。
原文地址:https://dev.to/fullstackcafe/45-important-php-interview-questions-that-may-land-you-a-job-1794
推薦學習:《》
以上就是45 個必知必會的 PHP 面試題的詳細內容,更多請關注TW511.COM其它相關文章!