When to instantiate and when not to instantiate the object?

Asked

Viewed 403 times

0

Watching a video lesson PHP I learned that you can use a class in two ways, without instantiating the object and 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 to instantiate and when not to instantiate the object?

  • Note that the first with :: you just called a static method and it usually works only with static, usually emits a notice if you don’t use static, this is common in other languages as well.

  • I know the questions seem different, but the answer there explains the doubt, I think.

1 answer

2

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

On the other hand, classes that need to be instantiated are usually designed to represent oneness.
A classic example of this is a PERSON class, for example, where each person is represented through 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 agreed that there is here a real need to create an instance to represent each person, the concept of person, there is a representation of identity.

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

Browser other questions tagged

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