广告
返回顶部
首页 > 资讯 > 后端开发 > PHP编程 >45 个必知必会的 PHP 面试题
  • 369
分享到

45 个必知必会的 PHP 面试题

2024-04-02 19:04:59 369人浏览 八月长安
摘要

本篇文章给大家总结了45 个必知必会的 PHP 面试题 。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。php零基础到就业直播视频课:进入学习程序员必备接口测试调试工具:立即使用Q1: == 和 === 之间有什么区别?#

本篇文章给大家总结了45 个必知必会的 PHP 面试题 。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

php零基础到就业直播视频课:进入学习
程序员必备接口测试调试工具:立即使用

Q1: == 和 === 之间有什么区别?#

话题: PHP
困难: ⭐

  • 如果是两个不同的类型,运算符 == 则在两个不同的类型之间进行强制转换
  • === 操作符执行’类型安全比较

这意味着只有当两个操作数具有相同的类型和相同的值时,它才会返回 TRUE。

1 === 1: true
1 == 1: true
1 === "1": false // 1 是一个整数, "1" 是一个字符串
1 == "1": true // "1" 强制转换为整数,即1
"foo" === "foo": true // 这两个操作数都是字符串,并且具有相同的值

? 源自: stackoverflow.com

Q2: 如何通过引用传递变量?#

话题: PHP
困难: ⭐

为了能够通过引用传递变量,我们在其前面使用 &,如下所示:

$var1 = &$var2

? 源自: guru99.com

Q3: $GLOBAL 是什么意思?#

话题: PHP
困难: ⭐

$GLOBALS 是关联数组,包含对脚本全局范围内当前定义的所有变量的引用。

? 源自: guru99.com

Q4: ini_set () 有什么用处?#

话题: PHP
困难: ⭐

PHP 允许用户使用 ini_set () 修改 php.ini 中提到的一些设置。此函数需要两个字符串参数。第一个是要修改的设置的名称,第二个是要分配给它的新值。

给定的代码行将启用脚本的 display_error 设置 (如果它被禁用)。

ini_set('display_errors', '1');

我们需要将上面的语句放在脚本的顶部,以便该设置一直保持启用状态,直到最后。此外,通过 ini_set () 设置的值仅适用于当前脚本。此后,PHP 将开始使用 php.ini 中的原始值。

? 源自: GitHub.com/Bootsity

Q5: 我应该在什么时候使用 require 和 include 呢?#

话题: PHP
困难: ⭐⭐

require() 函数与 include() 函数相同,只是它处理错误的方式不同。如果出现错误,include() 函数会生成警告,但脚本会继续执行。require() 函数会产生致命错误,脚本会停止。

我的建议是 99.9% 的时间里只使用 require_once

使用 requireinclude 代替意味着您的代码在其他地方不可重用,即您引入的脚本实际上是在执行代码,而不是提供类或某些类功能库。

? Source: stackoverflow.com

Q6: PHP 中的 stdClass 是什么?#

主题: 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

Q7: PHP 中的 die () 和 exit () 函数有什么不同?#

话题: PHP
困难: ⭐⭐

没有区别,它们是一样的。 选择 die() 而不是 exit() 的唯一好处可能是你节省了额外键入一个字母的时间.

? 源自: stackoverflow.com

Q8: 它们之间的主要区别是什么#

话题: PHP
困难: ⭐⭐

constdefine 的根本区别在于,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

Q9: isset () 和 array_key_exists () 之间有什么区别?#

话题: PHP
困难: ⭐⭐

  • array_key_exists 它会告诉你数组中是否存在键,并在 $a 不存在时报错。
  • 如果 key 或变量存在且不是 nullisset 才会返回 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

Q10: var_dump () 和 print_r () 有什么不同?#

话题: 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

Q11: 解释不同的 PHP 错误是什么#

话题: PHP
困难: ⭐⭐

  • notice 不是一个严重的错误,它说明执行过程中出现了一些错误,一些次要的错误,比如一个未定义的变量。
  • 当出现更严重的错误,如 include () 命令引入不存在的文件时,会给出警告 warning。 这个错误和上面的错误发生,脚本都将继续。
  • fatal error 致命错误将终止代码。未能满足 require () 将生成这种类型的错误。

? 源自: pangara.com

Q12: 如何在 PHP 中启用错误报告?

话题: PHP
困难: ⭐⭐

检查 php.ini 中的 “display_errors” 是否等于 “on”,或者在脚本中声明 “ini_set('display_error',1)”。

然后,在你的代码中包含 “ERROR_REPORTING(E_ALL)”,以便在脚本执行期间显示所有类型的错误消息。
? 源自: codementor.io

Q13: 使用默认参数声明某些函数

话题: PHP
困难: ⭐⭐

思考:

function showMessage($hello = false){
  echo ($hello) ? 'hello' : 'bye';
}

? 源自: codementor.io

Q14: PHP 是否支持多重继承?

话题: PHP
困难: ⭐⭐

PHP 只支持单一继承;这意味着使用关键字’extended’只能从一个类扩展一个类。

? 源自: guru99.com

Q15: 在 PHP 中,对象是按值传递还是按引用传递?

话题: PHP
困难: ⭐⭐

在 PHP 中,通过传递的对象。

? 源自: guru99.com

Q16:$a != $b 和 $a !== $b ,之间有什么区别?

话题: PHP
困难: ⭐⭐

!= 表示 不等于 (如果 $a 不等于 $b,则为 True), !== 表示 不全等 (如果 $a 与 $b 不相同,则为 True).

? 源自: guru99.com

Q17: 在 PHP 中,什么是 PDO?

话题: PHP
困难: ⭐⭐

PDO 代表 PHP 数据对象。

它是一组 PHP 扩展,提供核心 PDO 类和数据库、特定驱动程序。它提供了供应商中立、轻量级的数据访问抽象层。因此,无论我们使用哪种数据库,发出查询和获取数据的功能都是相同的。它侧重于数据访问抽象,而不是数据库抽象。

? 源自: github.com/Bootsity

Q18: 说明我们如何在 PHP 中处理异常?

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

Q19: 区分 echo 和 print ()

Topic: PHP
Difficulty: ⭐⭐

echoprint 基本上是一样的。他们都是用来打印输出数据的。

区别在于:

  • echo 没有返回值,而 print 的返回值为 1,因此 print 可以在表达式中使用。
  • echo 可以接受多个参数一起输出 (但是这种多个的输出方式很少见),而 print 一次只可以输出一个参数。
  • echo 的输出比 print 效率要高一些 .

? Source: github.com/Bootsity

Q20: require_once 和 require 在什么场景下使用?

Topic: PHP
Difficulty: ⭐⭐⭐

require_once() 作用与 require() 的作用是一样的,都是引用或包含外部的一个 php 文件,require_once() 引入文件时会检查文件是否已包含,如果已包含,不再包含 (require) 它。

我建议在 99.9% 的时候要使用 require_once

使用 requireinclude 意味着您的代码不可在其他地方重用,即您要拉入的脚本实际上是在执行代码,而不是提供类或某些函数库。

? Source: stackoverflow.com

Q21: 判断 PHP 数组是否是关联数组

Topic: PHP
Difficulty: ⭐⭐⭐

思考:

function has_string_keys(array $array) {
  return count(array_filter(array_keys($array), 'is_string')) > 0;
}

如果 $array 至少有一个字符串类型的 key ,它将被视为关联数组。

? Source: stackoverflow.com

Q22: 如何将变量和数据从 PHP 传至 Javascript

Topic: PHP
Difficulty: ⭐⭐⭐

这里有几种实现方法:

  • 使用 ajax 从服务端获取你需要的数据。

思考 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>
  • 可以在网页任何地方输出数据,然后使用 javascript 从 DOM 中获取信息.
<div id="dom-target" style="display: none;">
    <?php
        $output = "42"; // 此外, 做一些操作,获得 output.
        echo htmlspecialchars($output); 
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
  • 直接在 JavaScript 代码中 echo 数据。
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; // Don't forget the extra semicolon!
</script>

? Source: stackoverflow.com

Q23: 有一个方法可以复制一个 PHP 数组至另一个数组吗?

Topic: PHP
Difficulty: ⭐⭐⭐

PHP 数组通过复制进行赋值,而对象通过引用进行赋值。所有默认情况下,PHP 将复制这个数组。这里有一个 PHP 参考,一目了然:

$a = array(1,2);
$b = $a; // $b 是一个不同的数组
$c = &$a; // $c 是 $a 的引用

? Source: stackoverflow.com

Q24: What will be returned by this code?

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

Q25: What will be returned by this code? Explain the result.

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

Q26: What exactly is the the difference between array_map, array_walk and array_filter?

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

Q27: Explain the difference between exec() vs system() vs passthru()?

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

Q28: How would you create a Singleton class using PHP?

Topic: PHP
Difficulty: ⭐⭐⭐


final class UserFactory {
    
    public static
    function Instance() {
        static $inst = null;
        if ($inst === null) {
            $inst = new UserFactory();
        }
        return $inst;
    }

    
    private
    function __construct() {

    }
}

To use:

$fact = UserFactory::Instance();
$fact2 = UserFactory::Instance();

But:

$fact = new UserFactory()

Throws an error.

? Source: stackoverflow.com

Q29: What is the difference between PDO’s query() vs execute()?

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

Q30: What is use of Null Coalesce Operator?

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

Q31: Differentiate between exception and error

Topic: PHP
Difficulty: ⭐⭐⭐

  • Recovering from 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.
  • You will not be able to handle the 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

Q32: What are the exception class functions?

Topic: PHP
Difficulty: ⭐⭐⭐

There are following functions which can be used from Exception class.

  • getMessage() − message of exception
  • getCode() − code of exception
  • getFile() − source filename
  • getLine() − source line
  • getTrace() − n array of the backtrace()
  • getTraceAsString() − formated string of trace
  • Exception::__toString gives the string representation of the exception.

? Source: github.com/Bootsity

Q33: Differentiate between parameterised and non parameterised functions

Topic: PHP
Difficulty: ⭐⭐⭐

  • Non parameterised functions don’t take any parameter at the time of calling.
  • Parameterised functions take one or more arguments while calling. These are used at run time of the program when output depends on dynamic values given at run time There are two ways to access the parameterised function:
    • 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

Q34: Explain function call by reference

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

Q35: Why do we use extract()?

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

Q36: explain what is a closure in PHP and why does it use the “use” identifier?

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.
  • You can pass in variables as pointers like in case of &$total. This way, modifying the value of $total DOES HAVE an external effect, the original variable’s value changes.

? Source: stackoverflow.com

Q37: What exactly are late static bindings in PHP?

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

Q38: How to measure execution times of PHP scripts?

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

Q39: What is the best method to merge two PHP objects?

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

Q40: Compare mysqli or PDO - what are the pros and cons?

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

Q41: What is use of Spaceship Operator?

Topic: PHP
Difficulty: ⭐⭐⭐⭐

This <=> operator will offer combined comparison in that it will:

  • Return 0 if values on either side are equal
  • Return 1 if value on the left is greater
  • Return -1 if the value on the right is greater

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

Q42: Does PHP have threading?

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

Q43: Is PHP single or multi threaded?

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

Q44: Provide some ways to mimic multiple constructors in PHP

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.

    
    public function __construct() {
        // allocate your stuff
    }

    
    public static function create() {
        $instance = new self();
        return $instance;
    }

    
    public function setFirstName( $firstName) {
        $this->firstName = $firstName;
        return $this;
    }

    
    public function setLastName( $lastName) {
        $this->lastName = $lastName;
        return $this;
    }
}

// create instance
$student= Student::create()->setFirstName("John")->setLastName("Doe");

? Source: stackoverflow.com

Q45: How could we implement method overloading in PHP?

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));
    }
}


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 面试题的详细内容,更多请关注编程网其它相关文章!

--结束END--

本文标题: 45 个必知必会的 PHP 面试题

本文链接: https://www.lsjlt.com/news/34103.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 45 个必知必会的 PHP 面试题
    本篇文章给大家总结了45 个必知必会的 PHP 面试题 。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。php零基础到就业直播视频课:进入学习程序员必备接口测试调试工具:立即使用Q1: == 和 === 之间有什么区别?#...
    99+
    2022-09-20
  • GO必知必会的常见面试题汇总
    目录引言值类型和引用类型值类型有哪些引用类型有哪些?值类型和引用类型的区别?垃圾回收一图胜千言堆和栈栈堆切片比较比较的详解深拷贝和浅拷贝操作对象区别如下:new和makenew特点举...
    99+
    2022-11-11
  • AJAX必会面试题有哪些
    这篇文章主要为大家展示了“AJAX必会面试题有哪些”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“AJAX必会面试题有哪些”这篇文章吧。1、什么是AJAX,为什么...
    99+
    2022-10-19
  • 【MySQL数据库】2022年MySQL必知必会,基础内容与常见面试题
    大家好,我是ly甲烷😜 经过三次整理修改,更有逻辑更易记忆的MySQL面试总结,👇👇 有用可以收藏❤️,我相信这个早晚能帮到你 文章目录 ...
    99+
    2023-09-01
    数据库 mysql 面试
  • 必须要会的React面试题有哪些
    本篇内容主要讲解“必须要会的React面试题有哪些”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“必须要会的React面试题有哪些”吧!基本知识1. 区分Real...
    99+
    2022-10-19
  • Linux运维MySQL必会面试题100道
    1.开启MySQL服务 2.检测端口是否运行 3.为MySQL设置密码或者修改密码。 4.登陆MySQL数据库。 5.查看当前数据库的字符集 6.查看当前数据库版本 7.查看当前登录的用户。 8.创建GBK...
    99+
    2022-10-18
  • Python开发面试题:面试中 8 个必考问题
    ‘’金三银四‘’工作的人没有不知道的吧,其实7月也是跳槽面试的高峰期,咱们的学生大军也加入了找工作的浪潮。这里根据经验和实际情况总结了一下在Python面试中,关于Python开发面试题必考的8个问题,有需要的小伙伴,敲黑板认真看哦!...
    99+
    2023-06-02
  • 最新Mysql大厂面试必会的34问题
    1、mysql的隔离级别 2、MYSQL性能优化 常用5种方式 3、索引详解 1、何为索引,有什么用? 2、索引的优缺点 4、什么情况下需要建索引? 5、什么情况下不建索引? 6、索引的底层数据结构 1、...
    99+
    2018-12-18
    最新Mysql大厂面试必会的34问题
  • web前端工程师面试题10条必会笔试题
    布局 左边20% 中间自适应 右边200px 不能用定位答案:圣杯布局/双飞翼布局或者flex什么叫优雅降级和渐进增强?渐进增强 progressive enhancement:针对低版本浏览器进行构建页面,保证最基本的...
    99+
    2023-06-05
  • [译]Python面试中8个必考问题
    1、下面这段代码的输出结果是什么?请解释。 def extendList(val, list=[]): list.append(val) return list list1 = extendList(10) list2 ...
    99+
    2023-01-31
    Python
  • Go API 教程面试前必须知道的 5 个关键问题
    Go是一种快速、高效、简单的编程语言,被广泛应用于网络编程、云计算和大数据等领域。在面试中,如果你有Go语言的开发经验,并且能够熟练地编写API,那么你将会成为面试官眼中的宝贵人才。本文将介绍面试前必须了解的5个关键问题,帮助你更好地掌握G...
    99+
    2023-07-28
    面试 教程 api
  • 面试前必须要知道的21道Redis面试题是什么
    本篇内容介绍了“面试前必须要知道的21道Redis面试题是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!使用redis有哪些好处?速度快...
    99+
    2023-06-04
  • 【整理汇总】45+个Vue面试题,带你巩固知识点!
    本篇文章给大家总结分享一些Vue面试题(附答案解析),带你梳理基础知识,增强Vue知识储备,值得收藏,快来看看吧!1. 简述 Vue 生命周期答题思路:Vue 生命周期是什么?Vue 生命周期有哪些阶段?Vue 生命周期的流程?结合实践扩展...
    99+
    2023-05-14
    面试题 Vue.js
  • Linux运维必会的MySQL企业面试题大全 推荐
    Linux运维必会的MySQL企业面试题大全 推荐 (1)基础笔试命令考察1.开启MySQL服务/etc/init.d/mysqld st...
    99+
    2022-10-18
  • 面试中 PHP HTTP 相关问题必须知道的文件有哪些?
    在 PHP 程序中,HTTP 协议是非常重要的组成部分,因为它是浏览器和服务器之间通信的协议。因此,在 PHP 面试中,HTTP 相关问题是必须了解的。在本文中,我们将介绍面试中 PHP HTTP 相关问题必须知道的文件。 $_GET ...
    99+
    2023-09-19
    http 面试 文件
  • 2020面试必知:中高级工程师面试题集整理(题目+答案)
    这些面试题是我准备换工作的时候整理,没有重点。包括java基础,数据结构,网络,Android相关等等。...
    99+
    2023-06-04
  • PHP 面试中必备的打包 API 知识是什么?
    PHP 是一种常用的服务器端编程语言,常用于 Web 开发和构建动态网站。当你准备参加面试时,掌握一些常用的打包 API 知识是非常重要的。这篇文章将介绍 PHP 面试中必备的打包 API 知识。 ZipArchive 类 ZipArc...
    99+
    2023-08-22
    面试 打包 api
  • 「UNIX 环境下 GO 框架面试攻略」——你必须知道的几个问题!
    UNIX 环境下 GO 框架面试攻略——你必须知道的几个问题! 在当今互联网时代,GO 语言已成为了最受欢迎的编程语言之一。在这个语言中,GO 框架也成为了开发者们最常用的工具之一。如果你正在寻找一份 GO 框架的工作,那么你一定需要准备好...
    99+
    2023-11-12
    框架 面试 unix
  • 前端面试必会网络跨域问题解决方法
    目录什么是跨域跨域解决方法1-代理跨域解决方法2-JSONP跨域解决方法3-CORS概述简单请求简单请求的判定简单请求的交互规范需要预检的请求附带身份凭证的请求一个额外的补充什么是跨...
    99+
    2022-11-13
  • Python必考的5道面试题集合
    1、使用while循环实现输出2 - 3 + 4 - 5 + 6 ... + 100的和 #方法一 #从2开始计算 i = 2 #定义一个变量用于保存结果 sum=0 while i...
    99+
    2022-11-11
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作