How to Instantiate a PHP Class

Asked

Viewed 1,157 times

0

Usually to instantiate and use a class in my project, I use:

include ('arquivo_que_contem_a_classe.php'); 
$obj = new obj(); 
$obj->nomedafunction();

But today I needed a ready-made class downloaded from github via Composer, which created some directories and an autoload.php file.

In the example of using this class, pde to use as follows:

$obj = new \dir1\dir1\dir3([
  'var1'        =>  'var1', 
  'var2'    =>  'var2', 
  'var3'   =>  'var3', 
  'var4'    =>  'var4']); 

$executa = $obj->nomedafunction(); 

I don’t understand the method of instantiating this class. I don’t know how to Google this, so I’m here asking for a force to explain to me how it works.

Note: The above codes are just examples.

  • What you don’t understand?

  • Thank you for the answer. I didn’t understand why you don’t have a file include that contains the class and what those " dir1 dir1 dir3".

  • It must have it somewhere. Or the class is set just above the code, there is no miracle. That would be namespace.

  • Composer autoload will take care of including the file for you. Just search for "PHP autoload" or more specifically PSR 4.

1 answer

3


This is a feature called namespace

http://php.net/manual/en/language.namespaces.php

It serves to separate your classes logically, but they need to be "included" in the same way ... but the autoload of Poser already does this for you, so you only need to refer to them in this way

Browser other questions tagged

You are not signed in. Login or sign up in order to post.