Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I instantiate a PHP class inside another class?

I was wondering if it is allowed to create an instance of a class inside another class.

Or, do I have to create it outside and then pass it in through the constructor? But then I would have created it without knowing if I would need it.

Example (a database class):

class some{  if(.....){ include SITE_ROOT . 'applicatie/' . 'db.class.php'; $db=new db 
like image 501
Richard Avatar asked Oct 17 '09 20:10

Richard


People also ask

Can you instantiate a class within another class?

Yes you definitely can instantiate a class inside a constructor method of another class.

Can we create class inside class in PHP?

PHP 7 has introduced a new class feature called the Anonymous Class which will allow us to create objects without the need to name them. Anonymous classes can be nested, i.e. defined inside other classes. Read this article to learn how to defined and use anonymous classes nested inside other classes.

How can we use one class in another class in PHP?

The public keyword is used in the definition of the class, not in a method of the class. In php, you don't even need to declare the member variable in the class, you can just do $this->tasks=new tasks() and it gets added for you.

How do you instantiate an object with a different class?

Instantiating a ClassThe new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object. The new operator returns a reference to the object it created.


2 Answers

You can't define a class in another class. You should include files with other classes outside of the class. In your case, that will give you two top-level classes db and some. Now in the constructor of some you can decide to create an instance of db. For example:

include SITE_ROOT . 'applicatie/' . 'db.class.php';  class some {      public function __construct() {         if (...) {             $this->db = new db;         }     }  } 
like image 120
Lukáš Lalinský Avatar answered Oct 08 '22 18:10

Lukáš Lalinský


People saying that it is possible to 'create a class within a class' seem to mean that it is possible to create an object / instance within a class. I have not seen an example of an actual class definition within another class definition, which would look like:

class myClass{      class myNestedClass{      }  }  /* THIS IS NOT ALLOWED AND SO IT WON'T WORK */ 

Since the question was 'is it possible to create a class inside another class', I can now only assume that it is NOT possible.

like image 26
vincentDV Avatar answered Oct 08 '22 20:10

vincentDV