Justin
Justin

Reputation: 45350

PHP Define a class only allowed to be instantiated by another class

Is there a way in PHP to make a class only allowed to be instantiated by another class? For example:

<?php 
    class Graph {
        private $nodes;

        public function __construct() {
            $this->nodes = array();
        }

        public function add_node() {
            $this->nodes[] = new Node();
        }
    }

    class Node {
        public function __construct() {
        }
    }
?>

In my example I want to prevent access to calling new Node() directly. Only access to Node should be from the Graph class.

Thanks.

Upvotes: 2

Views: 61

Answers (1)

artragis
artragis

Reputation: 3713

No, you can't do it. You can use a "hack" which consist in throwing an exception in the Node constructor if the argument passed to it is not a graph

class Node {
    public function __construct() {
        if(func_get_num_args() < 1 && !(func_get_args(0)instanceof Graph)){
           throw BadCallException('You can\'t call Node outside a Graph');
        } 
    }
}

Upvotes: 3

Related Questions