When instantiating and when not instantiating the object? [duplicate]

0

I've learned a lesson from PHP that you can use a class in two ways, without instantiating instantiating the object .

// Forma 1    
echo SEO_URL::Strip('Caçador mata leão na selva');

// Forma 2
$url = new SEO_URL();
$url->Strip('Caçador mata leão na selva');

When instantiating and when not instantiating the object?

    
asked by anonymous 01.11.2015 / 15:14

1 answer

2

In what you call "Form 1 " (or class not instantiated) is nothing more than a simple "wrapper" for a set of operations or definitions, it's even easier to think of it as a small toolbox or utilities, hence why there are so common Utilities or Utils class that most of the times do not need to be instantiated.

On the other hand, classes that need to be instantiated are usually designed to represent uniqueness. A classic example of this is a PERSON class, for example, where each person is represented by a single object:

class Pessoa 
{
    public $cpf;
    public $name;

    public function __construct($nome, $cpf)
    {
        // ...
    }
}

$pessoas = array(
    new Pessoa('João', '000'), 
    new Pessoa('Pedro', '111'),
);

It must be said that there is a real need here to create an instance to represent each person, the concept of person, there is a identity representation.

Specifically your case, if the class SEO_URL is just a class that houses a set of common operations and there is a real need for identity, okay not to create an instance of it and call the methods statically (of course, assuming it so they were defined).

    
01.11.2015 / 16:05