использование переменной stati c в свойстве method vs stati c - PullRequest
0 голосов
/ 17 июня 2020

Два примера:

class StaticProperty 
{
    private static $staticProperty;

    private function someFunction()
    {
        if (null === self::$staticProperty) {
            //...havy work.
            self::$staticProperty = $result;
        }
        return self::$staticProperty;

    }
}

vs

class StaticVariable 
{
    private function someFunction()
    {
        static $staticVar;

        if (null === $staticVar) {
            //...havy work.
            $staticVar = $result;
        }
        return $staticVar;

    }
}

Есть ли разница между этими примерами? Свойство stati c используется только в одном методе класса.

Спасибо за ответы.

1 Ответ

1 голос
/ 19 июня 2020

Посмотрите на этот пример, главное отличие состоит в том, что у вас нет доступа в другом методе к c значению, объявленному внутри функции

<?php

class StaticProperty 
{
    private static $staticProperty = 'init property';

    private function someFunction()
    {
        if ('init property' === self::$staticProperty) {
            //...havy work.
            self::$staticProperty = 'my result in property';
        }
        return self::$staticProperty;

    }

    public function getResult()
    {
        var_dump(self::$staticProperty);
        return $this->someFunction();
    }
}

class StaticVariable 
{
    private function someFunction()
    {
        static $staticVar = 'init variable';

        if ('init variable' === $staticVar) {
            //...havy work.
            $staticVar = 'my result in variable';
        }
        return $staticVar;

    }

    public function getResult()
    {
        //var_dump(self::$staticVar);// it will call "Uncaught Error: Access to undeclared static property:.."
        return $this->someFunction();
    }
}

$staticVariable = new StaticVariable();
var_dump($staticVariable->getResult());

$staticPropertyClass = new StaticProperty();
var_dump($staticPropertyClass->getResult());

Результат:

string(21) "my result in variable"
string(13) "init property"
string(21) "my result in property"
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...