douxiong0668 2015-01-02 17:22 采纳率: 100%
浏览 21

使用静态方法和静态属性作为`global`

Is there anything wrong with this practice example?

class Test {
    static $_instance = null; // self
    protected $_name = null;


    /**
     * Get instance
     * @return [type] [description]
     */

        public static function getInstance() {
            if(is_null(self::$_instance))
                self::$_instance = new self;

            return self::$_instance;
        }

    /**
     * Set name
     */

        public static function setName($name) {
            self::getInstance()->_name = $name;
        }

        public static function getName() {
            return self::getInstance()->_name;
        }
}

And then doing this anywhere:

Test::setName('Some name');

Test::getName(); // returns "Some name"

Instead of:

// somewhere early
$test = new Test;

// somewhere else
function someRandomFunction() {
    global $test;

    $test->setName('Hello there');
}

// somewhere else
function AnotherRandomFunction() {
    global $test;

    return $test->getName();
}

I wrote a test that looks like this:

class TestTest extends WP_UnitTestCase {


    function testInstance() {
        $someName = 'Hello ' . time();

        Test::setName($someName);

        $this->assertEquals(Test::getName(), $someName);
    }
}

This being my very first test I write, I am unsure whether my test and approach to this is considered good practice.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 对于这个复杂问题的解释说明
    • ¥50 三种调度算法报错 采用的你的方案
    • ¥15 关于#python#的问题,请各位专家解答!
    • ¥200 询问:python实现大地主题正反算的程序设计,有偿
    • ¥15 smptlib使用465端口发送邮件失败
    • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
    • ¥15 对于squad数据集的基于bert模型的微调
    • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
    • ¥20 steam下载游戏占用内存
    • ¥15 CST保存项目时失败