How to create an object of a class from another class in php?

Member

by samara , in category: PHP General , a year ago

How to create an object of a class from another class in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , a year ago

@samara 

To create an object of a class from another class in PHP, you can follow these steps:

  1. Declare and define the first class, which you want to instantiate in the other class. class MyClass { // properties and methods of MyClass }
  2. Declare and define the second class, from which you want to create an object of the first class. class AnotherClass { // properties and methods of AnotherClass public function createObject() { $obj = new MyClass(); // create an object of MyClass // use the $obj as required } }
  3. Inside a method of the second class, you can then create an instance of the first class using the new keyword. $obj = new MyClass(); // create an object of MyClass


Note: Ensure that the declaration and definition of the first class (MyClass) is present and accessible within the second class (AnotherClass).