1.2.104. Can’t Instantiate Class

When constructor is not public, it is not possible to instantiate such a class. Either this is a conception choice, or there are factories to handle that. Either way, it is not possible to call new on such class.

<?php

//This is the way to go
$x = X::factory();

//This is not possible
$x = new X();

class X {
    //This is also the case with proctected __construct
    private function __construct() {}

    static public function factory() {
        return new X();
    }
}

?>

See also In a PHP5 class, when does a private constructor get called?, Named Constructors in PHP and PHP Constructor Best Practices And The Prototype Pattern.

1.2.104.2. Connex PHP features

1.2.104.2.1. Suggestions

  • Make the constructor public

  • Create a factory, as a static method, in that class, to create objects

  • Remove the new call

1.2.104.2.2. Specs

Short name

Classes/CantInstantiateClass

Rulesets

All, Analyze, Changed Behavior

Exakat since

1.2.8

PHP Version

All

Severity

Critical

Time To Fix

Quick (30 mins)

Precision

High

Examples

WordPress

Available in

Entreprise Edition, Exakat Cloud