[PHP] Multiple constructors in PHP > Web/PHP/API

본문 바로가기
사이트 내 전체검색

Web/PHP/API

[PHP] Multiple constructors in PHP

페이지 정보

작성자 sbLAB 댓글 0건 조회 3,079회 작성일 23-01-02 16:38

본문

Multiple constructors in PHP 

https://www.amitmerchant.com/multiple-constructors-php/


    <?php

    class Animal
    {
        public function __construct()
        {
            $arguments = func_get_args();
            $numberOfArguments = func_num_args();

            if (method_exists($this, $function = '__construct'.$numberOfArguments)) {
                call_user_func_array(array($this, $function), $arguments);
            }
        }
   
        public function __construct1($a1)
        {
            echo('__construct with 1 param called: '.$a1.PHP_EOL);
        }
   
        public function __construct2($a1, $a2)
        {
            echo('__construct with 2 params called: '.$a1.','.$a2.PHP_EOL);
        }
   
        public function __construct3($a1, $a2, $a3)
        {
            echo('__construct with 3 params called: '.$a1.','.$a2.','.$a3.PHP_EOL);
        }
    }

    $o = new Animal('sheep');
    $o = new Animal('sheep','cat');
    $o = new Animal('sheep','cat','dog');

    // __construct with 1 param called: sheep
    // __construct with 2 params called: sheep,cat
    // __construct with 3 params called: sheep,cat,dog

 

댓글목록

등록된 댓글이 없습니다.

회원로그인

접속자집계

오늘
34
어제
407
최대
1,279
전체
211,804

그누보드5
Copyright © sebom.com All rights reserved.