Heim  >  Fragen und Antworten  >  Hauptteil

构造函数不可以私有化吗?

这个为什么会报错?

<?php
class A{  
public $a=2; 
 private function __construct(){      
$this->a=4;  }}
$obj =new A();
echo $obj->a;


phpcn_u700phpcn_u7002808 Tage vor1316

Antworte allen(2)Ich werde antworten

  • 数据分析师

    数据分析师2017-10-01 00:15:32

    构造函数不可以私有化吗?-PHP中文网问答-构造函数不可以私有化吗?-PHP中文网问答

    围观一下哦,学习一下。

    Antwort
    0
  • 巴扎黑

    巴扎黑2017-02-10 11:30:53

    构造函数私有化后,不能再使用 new 外部调用,私有方法只能类内部使用。

    可以这样:

    <?php
    class A {  
    public $a = 2;  
    private function __construct(){      
    $this->a=4;  }  
    public static function createInstance() {   
       return new A();  }}
    $obj = A::createInstance();


    Antwort
    0
  • StornierenAntwort