This article summarizes 45PHPinterview questions that you must know and know. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
#Topic:PHP
Difficulty: ⭐
==
performs forced conversion between two different types===
The operator performs 'type safety Compare'This means it will return TRUE only if both operands have the same type and the same value.
1 === 1: true 1 == 1: true 1 === "1": false // 1 是一个整数, "1" 是一个字符串 1 == "1": true // "1" 强制转换为整数,即1 "foo" === "foo": true // 这两个操作数都是字符串,并且具有相同的值
?From:stackoverflow.com
#Topic:PHP
Difficulty: ⭐
To be able to quote viaTo pass a variable, we use&in front of it like this:
$var1 = &$var2
?From:guru99 .com
#Topic:PHP
Difficulty: ⭐
$GLOBALS
is an associative array containing references to all variables currently defined in the global scope of the script.
?From:guru99.com
#Topic:PHP allows users to use ini_set () Modify some settings mentioned in php.ini. This function requires two string parameters. The first is the name of the setting to be modified, and the second is the new value to be assigned to it. The given line of code will enable the script's display_error setting (if it is disabled).PHPDifficulty: ⭐
ini_set('display_errors', '1');
PHPrequire() TheDifficulty: ⭐⭐
function is the same as theinclude()
function, except how it handles errors. If an error occurs, theinclude()
function generates a warning, but the script continues execution.require()
The function will generate a fatal error and the script will stop.My advice is to just use
99.9% of the time.Using
orinclude
instead means your code is not reusable elsewhere, i.e. the script you include actually executes the code rather than providing the class Or some class function library.?
PHPstdClassDifficulty: ⭐⭐
Just a generic "empty" class used when casting other types to objects.stdClass
is not the base class for objects in PHP. This can be easily proven:
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
话题:PHP
困难: ⭐⭐
没有区别,它们是一样的。 选择die()
而不是exit()
的唯一好处可能是你节省了额外键入一个字母的时间.
话题: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()
—— 这仅仅是为了可读性!
话题: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
话题: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 )
话题: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 类和数据库、特定驱动程序。它提供了供应商中立、轻量级的数据访问抽象层。因此,无论我们使用哪种数据库,发出查询和获取数据的功能都是相同的。它侧重于数据访问抽象,而不是数据库抽象。
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&#39;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 (&#39;password123&#39; == $something) ? &#39;true&#39; : &#39;false&#39;;
The answer istrue
. 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
&#39;1e3&#39; == &#39;1000&#39; // 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 thingexceptthat 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 increasedsecurity. Aside from the escaping on the client-side that it provides, aprepared statement is compiledon 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 fromException
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 asErrors
are related to environment in which application is running.?Source:github.com/Bootsity
Topic:PHP
Difficulty: ⭐⭐⭐
There are following functions which can be used fromException
class.
getMessage()
− message of exceptiongetCode()
− code of exceptiongetFile()
− source filenamegetLine()
− source linegetTrace()
− n array of thebacktrace()
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 .= &#39;Call By Reference&#39;; } $str = &#39;This is &#39;; adder($str); echo $str;
Output:
This is Call By Reference
?Source:github.com/Bootsity
Topic:PHP
Difficulty: ⭐⭐⭐
Theextract()
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 aclosure. 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
)outsideof 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 theself
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 thestatic
keyword, which addresses this particular shortcoming. When you usestatic
, 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 &#39;Car&#39;; } } class Toyota extends Car { public static function getName() { return &#39;Toyota&#39;; } } 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 themicrotime
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 usearray_merge_recursive
to have adeep copybehavior.
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 usethe 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 avariadic functionthat takes in a variable number of arguments. You would usefunc_num_args()
andfunc_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(&#39;a&#39;, 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
推荐学习:《PHP视频教程》
The above is the detailed content of 45 must-know PHP interview questions. For more information, please follow other related articles on the PHP Chinese website!