Trait Singleton and invocation examples in PHP

Source: Internet
Author: User

Trait single case

Examples are as follows

<?phptrait Singleton {/** * private construct, generally defined by us ing class *///private function construct () {} public static function getinstance () {static $_instan        CE = NULL;        $class = class;    Return $_instance?: $_instance = new $class; Public Function Clone () {trigger_error (' cloning ').    CLASS. ' is not allowed. ', e_user_error); The Public Function wakeup () {trigger_error (' unserializing ').    CLASS. ' is not allowed. ', e_user_error);        }}/*** Example usage*/class foo {use singleton;    Private Function construct () {$this->name = ' foo ';        }}class Bar {use singleton;    Private Function construct () {$this->name = ' bar '; }} $foo = Foo::getinstance (), echo $foo->name; $bar = Bar::getinstance (); Echo $bar->name; 

Calling the Trait method

Although not obvious, if the trait method can be defined as a static method in a normal class, it can be called

Examples are as follows

<?php trait Foo {     function bar () {         return ' Baz ';     }} Echo Foo::bar (), "\\n";?>

Class and trait

Class returns the class name,trait of Use trait returns trait name

Examples such as the following

<?phptrait 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 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.