PHP is a class that can only be created by another class.

Imagine this scenario:

class Page {} class Book { private $pages = array(); public function __construct() {} public function addPage($pagename) { array_push($this->pages, new Page($pagename)); } } 

In any case, can I make sure that only the objects in my class book can create pages? For example, if a programmer tries something like:

 $page = new Page('pagename'); 

Does the script throw an exception?

thanks

+6
source share
4 answers

This is a little far-fetched, but you can use this:

 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 ); 
+4
source

Well, I see your thought, but with the tools provided by the language, this is not possible.

One thing you could do requires a Book object when creating the page:

 class Page { public function __construct( Book $Book ) {} } class Book { public function addPage() { $this->pages[] = new Page( $this ); } } 
+4
source

I think that most of all you can get to Page require Book as one of the constructor arguments and add it to this copy of the book. That way, you never float around Page , but they are always associated with some book (although it is still possible to have the same Page in many Book s.

 class Book { public function addPage($page) { if(is_a($page,'Page') { $this->pages->push($page); } else if (is_string($page)) { new Page($this,$page) } else { throw new InvalidArgumentException("Expected string or 'Page' - ".gettype($page)." was given instead"); } } } class Page { public function __construct(Book $book, $pagename) { $book->addPage($this); } } 

It looks ugly though ...: /

+2
source

Not. In PHP this is not possible. Even if it were possible, the developer could change his own needs and disable your release ...

+1
source

Source: https://habr.com/ru/post/895602/


All Articles