欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

trycatchfinally

程序员文章站 2022-07-14 10:26:56
...
<?php

function test()
{
    $str = "hello";
    try {
        return $str;
    } finally {
        $str = "world";
    }
}

function test1()
{
    $arr = new stdClass();
    $arr->name = 'silk';
    try {
        return $arr;
    } finally {
        $arr->name = "xiaoyang";
    }
}

function test2()
{
    $arr = [
        'name' => 'silk',
        'age' => 18
    ];
    try {
        return $arr;
    } finally {
        $arr['name'] = "xiaoyang";
    }
}

function test3()
{
    $i = 0;
    try {
        return ++$i;
    } finally {
        $i = $i + 2;
    }
}

function test4()
{
    $i = 0;
    try {
//        return ++$i;
        throw new Exception("new Exception");
    } catch (Exception $e) {
        return --$i;
    } finally {
        return --$i;
    }
}

var_dump(test());
var_dump(test1());
var_dump(test2());
var_dump(test3());
var_dump(test4());