Home  >  Article  >  Backend Development  >  Detailed explanation of trait singleton and calling instances in PHP

Detailed explanation of trait singleton and calling instances in PHP

伊谢尔伦
伊谢尔伦Original
2017-07-03 11:08:031169browse

Trait单例

实例如下

<?php
trait singleton {    
    /**
     * private construct, generally defined by using class
     */
    //private function construct() {}
    
    public static function getInstance() {
        static $_instance = NULL;
        $class = CLASS;
        return $_instance ?: $_instance = new $class;
    }
    
    public function clone() {
        trigger_error(&#39;Cloning &#39;.CLASS.&#39; is not allowed.&#39;,E_USER_ERROR);
    }
    
    public function wakeup() {
        trigger_error(&#39;Unserializing &#39;.CLASS.&#39; is not allowed.&#39;,E_USER_ERROR);
    }
}
/**
* Example Usage
*/
class foo {
    use singleton;
    
    private function construct() {
        $this->name = &#39;foo&#39;;
    }
}
class bar {
    use singleton;
    
    private function construct() {
        $this->name = &#39;bar&#39;;
    }
}
$foo = foo::getInstance();
echo $foo->name;
$bar = bar::getInstance();
echo $bar->name;

调用trait方法

虽然不很明显,但是如果Trait的方法可以被定义为在普通类的静态方法,就可以被调用

实例如下

<?php 
trait Foo { 
    function bar() { 
        return &#39;baz&#39;; 
    } 
} 
echo Foo::bar(),"\\n"; 
?>

CLASS和TRAIT

CLASS 返回 use trait 的 class name,TRAIT返回 trait name

示例如下

<?php
trait TestTrait {
    public function testMethod() {
        echo "Class: " . CLASS . PHP_EOL;
        echo "Trait: " . TRAIT . PHP_EOL;
    }
}
class BaseClass {
    use TestTrait;
}
class TestClass extends BaseClass {
}
$t = new TestClass();
$t->testMethod();
//Class: BaseClass
//Trait: TestTrait

The above is the detailed content of Detailed explanation of trait singleton and calling instances in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn