php中static关键字的作用是什么-PHP问题

资源魔 30 0

php中static要害字的作用是:一、放正在函数外部润饰变量,函数执行完后变量值依然保留;二、放正在类中润饰属性或办法,假如润饰的是类的属性,则保存值;三、放正在类的办法中润饰变量;四、润饰全局作用域的变量。

static要害字的作用以下:

一、放正在函数外部润饰变量;

二、放正在类里润饰属性或办法;

三、放正在类的办法里润饰变量;

四、润饰全局作用域的变量;

要害字所示意的没有同含意以下:

一、正在函数执行完后,变量值依然保留

以下所示:

<?php
function testStatic() {
    static $val = 1;
    echo $val;
    $val++;
}
testStatic();   //output 1
testStatic();   //output 2
testStatic();   //output 3
?>

二、润饰属性或办法,能够经过类名拜访,假如是润饰的是类的属性,保存值

以下所示:

<?php
class Person {
    static $id = 0;
 
    function __construct() {
        self::$id++;
    }
 
    static function getId() {
        return self::$id;
    }
}
echo Person::$id;   //output 0
echo "<br/>";
 
$p1=new Person();
$p2=new Person();
$p3=new Person();
 
echo Person::$id;   //output 3
?>

三、润饰类的办法外面的变量

以下所示:

<?php
class Person {
    static function tellAge() {
        static $age = 0;
        $age++;
        echo "The age is: $age
";
    }
}
echo Person::tellAge(); //output 'The age is: 1'
echo Person::tellAge(); //output 'The age is: 2'
echo Person::tellAge(); //output 'The age is: 3'
echo Person::tellAge(); //output 'The age is: 4'
?>

四、润饰全局作用域的变量,不实际意思

以下所示:

<?php
static $name = 1;
$name++;
echo $name;
?>
另外:思考到PHP变量作用域

<?php
include 'ChromePhp.php';
 
$age=0;
$age++;
 
function test1() {
    static $age = 100;
    $age++;
    ChromePhp::log($age);  //output 101
}
 
function test2() {
    static $age = 1000;
    $age++;
    ChromePhp::log($age); //output 1001
}
 
test1();
test2();
ChromePhp::log($age); //outpuut 1
?>

能够看出,这3个变量是没有互相影响的。另外,PHP外面只有全局作用域以及函数作用域,不块作用域。

假如您想学习更多相干常识,欢送拜访资源魔。

以上就是php中static要害字的作用是甚么的具体内容,更多请存眷资源魔其它相干文章!

标签: php php教程 Static php故障解决 php使用问题

抱歉,评论功能暂时关闭!