想象一下这种情况:
class Page {}
class Book {
private $pages = array();
public function __construct() {}
public function addPage($pagename) {
array_push($this->pages, new Page($pagename));
}
}
Run Code Online (Sandbox Code Playgroud)
无论如何,我可以确保只有我的班级书籍的对象可以实例化页面吗?就像,如果程序员尝试类似的东西:
$page = new Page('pagename');
Run Code Online (Sandbox Code Playgroud)
脚本抛出异常?
谢谢
好吧,我明白你的意思,但是使用该语言提供的工具,这是不可能的。
您可以做的一件事是在构造 Page 时需要一个 Book 对象:
class Page {
public function __construct( Book $Book ) {}
}
class Book {
public function addPage() {
$this->pages[] = new Page( $this );
}
}
Run Code Online (Sandbox Code Playgroud)
这有点做作,但你可以使用这个:
abstract class BookPart
{
abstract protected function __construct();
}
class Page
extends BookPart
{
private $title;
// php allows you to override the signature of constructors
protected function __construct( $title )
{
$this->title = $title;
}
}
class Book
extends BookPart
{
private $pages = array();
// php also allows you to override the visibility of constructors
public function __construct()
{
}
public function addPage( $pagename )
{
array_push( $this->pages, new Page( $pagename ) );
}
}
$page = new Page( 'test will fail' ); // Will result in fatal error. Comment out to make scrip work
$book = new Book();
$book->addPage( 'test will work' ); // Will work.
var_dump( $book );
Run Code Online (Sandbox Code Playgroud)