1.2.101. 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.101.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.101.2. Specs

Short name

Classes/CantInstantiateClass

Rulesets

All, Analyze

Exakat since

1.2.8

PHP Version

All

Severity

Critical

Time To Fix

Quick (30 mins)

Precision

High

Features

constructor, visibility

Examples

WordPress

Available in

Entreprise Edition, Exakat Cloud