21xrx.com
2025-04-01 01:52:38 Tuesday
文章检索 我的文章 写文章
【PHP 2021 面试题】——加深对 PHP 的理解
2023-06-18 20:52:03 深夜i     10     0
魔术方法 __construct __destruct __set __get __call __toString

PHP 作为一门流行的后端编程语言,在面试中也常常被考察。下面整理了一些 PHP 2021 面试题,希望对大家加深对 PHP 的理解和掌握有所帮助。

1. PHP 中的魔术方法有哪些?它们分别的作用是什么?

答案示例:

class MagicClass {
 private $name;
 
 public function __construct($name) {
  $this->name = $name;
 }
 
 public function __destruct()
  echo "Class destroyed";
 
 
 public function __set($field, $value) {
  $this->$field = $value;
 }
 
 public function __get($field) {
  return $this->$field;
 }
 
 public function __call($method, $args) {
  echo 'calling undefined method ' . $method . ' with arguments: ';
  print_r($args);
 }
 
 public function __toString() {
  return $this->name;
 }
}
$mc = new MagicClass('test');
$mc->age = 18;
echo $mc; // 输出 test
$mc->noMethod('test'); // 输出 calling undefined method noMethod with arguments: Array ( [0] => test )

2. 如何在 PHP 中实现单例模式?

关键词:单例模式、__construct、private、static

答案示例:

class Singleton {
 private static $instance = null;
 private function __construct()
  // 防止外部实例化
 public static function getInstance(){
  if(!self::$instance){
   self::$instance = new Singleton();
  }
  return self::$instance;
 }
}
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();
var_dump($instance1 === $instance2); // 输出 bool(true)

3. 请编写一个函数,输入一个数组,输出数组中最大的数。

关键词:PHP、函数、数组、最大值

答案示例:

function getMax($arr) {
 if (count($arr) === 0) return null;
 $max = $arr[0];
 for ($i = 1; $i < count($arr); $i++) {
  if ($max < $arr[$i]) $max = $arr[$i];
 }
 return $max;
}
$arr = array(1, 5, 9, 2, 4, 7);
echo getMax($arr); // 输出 9

以上就是几道 PHP 2021 面试题,希望对大家有所帮助。在学习的过程中,还需不断练习和总结,加强对所学知识的理解和掌握。

  
  

评论区

    相似文章