PHP面试题(二)

前言

从网上找了一套号称是百度的php面试题目,这里记录一下

PHP的gc机制

php的垃圾回收机制注意以下几点即可:
  • 引用计数refcount和is_ref,也就是php不会随意的malloc内存空间,而是用类似c的指针的方式,增加引用计数,引用计数为0就free掉变量,每个变量在底层实现都是一个在zval的结构体
  • php5.3之前无法解决循环引用计数的问题,会导致内存泄漏.php5.3以后,采用深度优先遍历解决了这个问题,具体实现细节我也不清楚

PHP实现单链表

<?php

/**
 * 用class模拟struct,实现链表节点定义
 */
class Node
{

    /**
     * 数据
     */
    public $data;

    /**
     * 下一个节点
     */
    public $next;

    public function __construct ($data, $next = null)
    {
        $this->data = $data;
        $this->next = $next;
    }
}

class LinkList
{

    public $head;

    public function __construct ()
    {
        $this->head = null;
    }

    /**
     * 尾插法实现链表插入操作
     *
     * @param int $value            
     */
    public function insertNode ($value)
    {
        $cur = $this->head;
        $pre = null;
        
        while ($cur != null) {
            $pre = $cur;
            $cur = $cur->next;
        }
        
        $new = new Node($value);
        $new->next = null;
        
        if ($pre == null) {
            $this->head = $new;
        } else {
            $pre->next = $new;
        }
    }

    /**
     * 单链表中删除指定节点
     *
     * @param int $value            
     */
    public function deleteNode ($value)
    {
        $cur = $this->head;
        $pre = null;
        
        while ($cur != null) {
            if ($cur->data == $value) {
                if ($pre == null) {
                    $this->head->next = $cur->next;
                } else {
                    $pre->next = $cur->next;
                }
                break;
            }
            $pre = $cur;
            $cur = $cur->next;
        }
    }

    /**
     * 打印单链表
     */
    public function printList ()
    {
        $cur = $this->head;
        while ($cur->next != null) {
            printf("%d ", $cur->data);
            $cur = $cur->next;
        }
        printf("%d
", $cur->data);
    }
}

// 测试
$list = new LinkList();
$list->insertNode(1);
$list->insertNode(2);
$list->insertNode(3);
$list->insertNode(4);
$list->insertNode(5);
$list->insertNode(6);

$list->printList();

$list->deleteNode(4);
$list->printList();

PHP实现字符串反转

<?php

function strReverse(&$str)
{
    for ($i = 0, $j = strlen($str); $i <= $j; $i ++, $j --) {
        $tmp = $str[$i];
        $str[$i] = $str[$j];
        $str[$j] = $tmp;
    }
}

$str = "wangzhengyi";
strReverse($str);
echo $str;

PHP变量的内部实现

编程语言的系统类型分为强类型和弱类型两种:
  • 强类型语言是一旦某个变量被申明为某个类型的变量,在程序运行过程中,就不能将该变量的类型以外的值赋予给它,c/c++/java等语言就属于这类
  • php及ruby,javascript等脚本语言就属于弱类型语言:一个变量可以表示任意的数据类型

php变量类型及存储结构



原文地址:https://www.cnblogs.com/keanuyaoo/p/3275746.html