Are protected constructors considered good practice?
Posted
by Álvaro G. Vicario
on Stack Overflow
See other posts from Stack Overflow
or by Álvaro G. Vicario
Published on 2010-06-08T09:55:25Z
Indexed on
2010/06/08
12:12 UTC
Read the original article
Hit count: 226
I'm writing some little helper classes to handle trees. Basically, I have a node and a special root node that represents the tree. I want to keep it generic and simple. This is part of the code:
<?php
class Tree extends TreeNode{
public function addById($node_id, $parent_id, $generic_content){
if( $parent = $this->findNodeById($parent_id) ){
$parent->addChildById($node_id, $generic_content);
}
}
}
class TreeNode{
public function __construct($node_id, $parent_id, $generic_content){
// ...
}
protected function addChildById($node_id, $generic_content){
$this->children[] = new TreeNode($this->node_id, $node_id, $generic_content);
}
}
$Categories = new Tree;
$Categories->addById(1, NULL, $foo);
$Categories->addById(2, NULL, $bar);
$Categories->addById(3, 1, $gee);
?>
My questions:
- Is it sensible to force
TreeNode
instances to be created throughTreeNode::addById()
? - If it's so, would it be good practise to declare
TreeNode::__construct()
as private/protected?
© Stack Overflow or respective owner