search
HomeBackend DevelopmentPHP TutorialPHP面试题碰到的几个坑。面壁ing

PHP面试题遇到的几个坑。...面壁ing

1.指针悬挂问题

$array = [1, 2, 3];

echo implode(',', $array), "\n";

foreach ($array as &$value) {}    // by reference

echo implode(',', $array), "\n";

foreach ($array as $value) {}     // by value (i.e., copy)

echo implode(',', $array), "\n";

正确答案应该是:

1,2,3

1,2,2

解释:

我们来分析下。第一个循环过后,$value是数组中最后一个元素的引用。第二个循环开始:

 

第一步:复制$arr[0]$value(注意此时$value$arr[2]的引用),这时数组变成[1,2,1]

第二步:复制$arr[1]$value,这时数组变成[1,2,2]

第三步:复制$arr[2]$value,这时数组变成[1,2,2]

 

 

2.以下结果输出:

$test=null;

if(isset($test)){

    echo "true";

}else{

    echo "false";

}

?>

正确答案:false

解释:对于 isset() 函数,变量不存在时会返回false,变量值为null时也会返回false

判断一个变量是否真正被设置(区分未设置和设置值为null),array_key_exists()函数或许更好。

3.以下结果能否打印出来,为什么?

class Config{

    private $values = [];

    public function getValues() {

        return $this->values;

    }

}

$config = new Config();

$config->getValues()['test'] = 'test';

echo $config->getValues()['test'];

正确答案:

不行,因为在PHP中,除非你显示的指定返回引用,否则对于数组PHP是值返回,也就是数组的拷贝。因此上面代码对返回数组赋值,实际是对拷贝数组进行赋值,非原数组赋值。如果把代码改成:

class Config{

    private $values = [];

    // return a REFERENCE to the actual $values array

    public function &getValues() {

        return $this->values;

    }

}

$config = new Config();

$config->getValues()['test'] = 'test';

echo $config->getValues()['test'];

就可以了。

知识要点:PHP中对于对象,默认是引用返回,数组和内置基本类型默认均按值返回。这个要与其它语言区别开来(很多语言对于数组是引用传递)。

4.以下代码运行后服务器输出什么?

$.ajax({

    url: 'http://my.site/ndex.php',

    method: 'post',

    data: JSON.stringify({a: 'a', b: 'b'}),

    contentType: 'application/json'

});

var_dump($_POST);

答案:array(0){}

解释:PHP仅仅解析Content-Type为 application/x-www-form-urlencoded 或 multipart/form-dataHttp请求。之所以这样是因为历史原因,PHP最初实现$_POST时,最流行的就是上面两种类型。因此虽说现在有些类型(比如application/json)很流行,但PHP中还是没有去实现自动处理。因为$_POST是全局变量,所以更改$_POST会全局有效。因此对于Content-Type为 application/json 的请求,我们需要手工去解析json数据,然后修改$_POST变量。

$_POST = json_decode(file_get_contents('php://input'), true);

这就解释了为什么微信公众平台开发时也要用这个方式获取微信服务器post的数据

 

 

6.以下代码输出的结果是:

for ($c = 'a'; $c 

    echo $c . "\n";

}

正确答案:a.......z,aa.....yz

解释:在PHP中不存在char数据类型,只有string类型。明白这点,那么对'z'进行递增操作,结果则为'aa'。对于字符串比较大小,学过C的应该都知道,'aa'是小于'z'的。这也就解释了为何会有上面的输出结果。

但是PHP中如果比较的是两个纯数字的字符串时,首先尝试将其当成数字来比较的。

版权声明:本文为博主原创文章,未经博主允许不得转载。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools