JavaScript and PHP factory functions

Source: Internet
Author: User
  • Javascript:
    A. Code:
    function createObj(name) {var obj = {    name:name,    showName:function(){        console.log(this.name)    }}return obj;}var obj1 = createObj(‘lee_1‘);var obj2 = createObj(‘lee_2‘);obj1.showName()obj2.showName()

    B. Output:

    lee_1lee_2
  • Php:
    A. Code:
    <?phpclass man{public function say(){    echo ‘我是男人‘.PHP_EOL;}}class women{public function say(){    echo ‘我是女人‘.PHP_EOL;}}class factory{static function createMan(){    return new man();}static function createWomen(){    return new women();}}$factory = new factory();$man = $factory->createMan();$man->say();$woman = $factory->createWomen();$woman->say();

    B. Output:

    我是男人我是女人
  • Description
    1、因为JS中没有类的概念,工厂函数是为了解决面向对象中的封装性而设计的2、PHP本身就是面向对象的语言,工厂函数只是为了防止new关键字使用过多,所以在PHP当中的工厂函数这个模式设计的很鸡肋,一般不用!
  • JavaScript and PHP factory functions

    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.