Is there a rule for "type statements in class properties"?

Asked

Viewed 154 times

5

PHP 7.4 supports type declarations in class properties.

In a normal routine I would use:

/* @var array */
protected $names;

Now in PHP 7.4 I can:

protected array $names;

But if I declare it this way I can’t initialize it as null, I would have to do:

protected ?array $names = null;

It’s wrong to do this?

In a class with many properties I can declare the type in all properties?

2 answers

8


Yes and no.

If there is the Feature then you can use it. But don’t use where you don’t need it.

Well, the question is much more complicated than this. Get into the PHP philosophy, or lack of.

Yes, PHP has suffered from lack of personality. This is one of the biggest criticisms that people who understand programming language do to PHP.

PHP was a language of dynamic typing simple and without ceremony, fantastic to do scripts for the web. One fine day they decided that it should become a language Nterprise to create complex websites. Great, right? That’s all people might want.

It does, but actually a language doesn’t change that strongly, especially it doesn’t change the part where it uses weak typing that’s the real problem with language typing. Dynamic typing is not a big problem, although it doesn’t make it as easy as code scale everything works well and gives a very interesting flexibility.

When PHP started to force itself into the type it created classes, interfaces (especially this one that only serves to type) and traits, allowed to put the data type more and more places, although in the background the type remains dynamic internally.

A class, in PHP, is not yet a real static type internally, but they are trying to make it look like this. The language does not yet have Generics which is an obligation to any language that tries to show itself to be static. But something tells me that they will create, even if it’s the wrong way to do it:

Quebra cabeças em relevo de letras de borracha com peças forçadas no lugar errado

Null makes sense?

Another point that breaks static typing is the nullity of the type. In really static languages allow a null value is an accepted datum it is as if the datum could have two types. In fact the most modern languages are avoiding the null, the so-called one billion dollar error, at least by default and you have to say that the null is a valid value when you really want the null. But since it’s a mistake you should never use... in a static typing language.

I call it my billion-dollar mistake. It was the invention of the null reference in 1965

I’m sorry if this pisses you off, but PHP is becoming a language freak, something very schizophrenic. It’s still a useful language, you can do a lot of things, but you can’t even tell what’s right or wrong to do in it.

It’s clearly being driven by people who look like children in a toy store who want to have everything they see and copy everything they have in other languages even if it doesn’t make sense in theirs.

Veruca Salt

So you have to decide what you’re going to do, whether you’re going to use the toy or not?

In another language it makes a lot of sense, but in PHP the typing is still dynamic and it doesn’t make much sense. But it is allowing to do.

If you are going to adopt the illusion of static typing you should avoid null, which can be a good one because one day they will break the compatibility of the language and make it static typing, you are already on the right track. I doubt it will happen, but clearly she was so jealous of Hack and wants to be her, only that does not want to lose the users who already have, that are many.

The error of Hack was to want to be a language well done and incompatible (still with a horrible and meaningless variable syntax).

I would always recommend avoiding the null at almost any cost. It is bad as already shown, and has links about. In some languages allow the null is the break that most happens. It is not fantastic if it is impossible to happen and it already get caught?

Of course it doesn’t help that the language isn’t compiled so the error will still be caught during execution, so the advantage isn’t great. You can only trust 100% if you make a 100% coverage code, which people say is a lot of work and most of the time you won’t. While PHP is not actually compiled, not just Jittada, the advantage will be much lower.

But to say that the semantics of that data can not accept null is a good one, because in general it is an accident the language allow the null in all cases.

Even languages that do not accept null correctly still allow you to opt for the type to be voidable, because there is a case that it makes sense. In a good design is extremely rare but always has, often because of database (which can also be avoided with good design, but it can be too hard and even create performance problems, so it doesn’t always pay to do).

Finally what you want to know

Your array then it can be null? Why? What is the advantage? You know of all the problems that this can give because it can be null? Why start something as null?

For me the solution is not to initialize the property as null, the correct is to put a array empty or with data there on building of it. This serves for most cases. If follow all links you’ll understand better.

I just don’t know how this will converse well with the rest of your code. Will you make all the code thinking about it? Will you only use libraries that used it that way? It is extremely difficult, not to say impossible, to make legacy code that the standard was voidable with a new one that the standard is not. If you start to allow the ? in all types to be able to communicate well with other codes, where the default is to accept null, then loses the reason to use it. But that’s true not only for the null, for anything involving, like,.

I think you should opt for one way or the other in 100% of the code, either adopt the typing or do not adopt. If not then it makes no sense to use classes, interfaces and other mechanisms that serve to further organize the type. If you adopt, don’t do it halfway, adopt nonnullity by default, only accept null if you have no better way (I can’t guarantee that your case will run out.

In the other answer shows a case that can be interesting to accept null type. In fact it is not bad, internally you guarantee that the data will only be accessed correctly and does not leak abstraction. But know that you can do that without the null. You have to create a variable that controls whether the object is initialized or not. Is that better? I don’t know, but it’s not a bad option. On the other hand nothing prevents initializing the object before and it always be available nor have to control whether it has already been initialized or not, for some reason some people think that it cannot.

I wouldn’t adopt static typing just because it’s never going to be good in dynamic typing language. But this is lost cause, PHP programmers have decided that they will follow cake recipes instead of thinking about what they are doing.

Completion

It’s a good one for me Feature and forces the programmer to be better, to think more about the design, start doing what is right and not just what works which is the standard of very PHP programmer

Fiat 147 todo detonado andando pelas ruas

The problem is that PHP wants to be Java or C#. So why not use those languages that are best suited to what it wants to be? These languages were thought to be Nterprise, if you want a language like this goes to one that has been so since its conception.

Otherwise, it only makes sense to use PHP the way it was originally designed. The way people are choosing to do it in PHP, because the language has allowed it to be more and more like this, it ends up with the worst of both worlds when trying to have the best of both worlds. You can’t have all the advantages of everything, and when you don’t choose which one you want to have you get something bad. And PHP can no longer choose to be Nterprise the right way, only if it’s another language, as Hack.

So people adopt the language for fallacious reasons. No problem adopting PHP, but you need to know why you’re doing it. People looking for this new PHP would get along better with another language, but the religious effect that happens to most people they can’t recognize it and will suffer for the rest of their lives.

These days I saw a language defense video that was full of falsehoods without even telling a lie. All to seem neutral and delight people "showing" how wonderful that language was, even if everyone who understands the subject says otherwise.

Símbolos religiosos

So think about what you want for yourself. If you are going to start using types, and I like it, use it correctly, learn to code correctly (PHP misuses people) and start giving the correct semantics, do not use null where you do not need.

I can’t tell you if this case needs a null, I don’t think so, but I can’t tell you, I can only answer that with a concrete case. One of the things that people don’t understand, especially when you do OOP, is that giving the correct semantics is the most desirable and most difficult to do. Almost nobody knows how to do it right, and again, you get the worst of the worlds, you create the bureaucracy of using a code full of strings and you don’t have a design good because she doesn’t understand what it really is to develop software. And it involves not believing that a cake recipe fits all cases. Developing software is making right decisions in every little detail of the process, and for this it takes deep knowledge of every aspect of computing.

If you’re tired of reading this maybe you don’t like the area that takes a lot of effort from people to get it right.

On the other hand, if you don’t care about it, and it doesn’t look like the AP case, you can do it anyway that will work, at least apparently.

I do not know the details, I imagine that for this to make sense you have to configure something that gives some error when you try to use a null when you can’t. And I don’t know what interoperability looks like with code that doesn’t use that way.

No problem the person programming in PHP, but to use the language correctly as it became, the person would have better benefits with another language.

Carro com um cavalo dentro com a cabeça pra fora

I don’t really like to use the phrase "the right tool for the task" because most tools work well for various problems, but this is a case that in the form used seems the wrong tool because it has a better one to do so. You’re using something that used to be a hammer and was doing well with nails and now you’re trying to do well with screws. Try using this:

Um tipo de canivete suíço com machado, martelo, etc.

I told you more about it on Quora.

Ah, almost always wear something protected is a mistake, along with null tends to be worse.

  • Well, I won’t disagree at all I found the answer well-crafted and thoughtful... As to the use of property being null is that it only becomes an array when I run another method, otherwise it is not even initialized, protected array $names = [] would be a good one? I’ve been in the PHP branch for 7 years and have always tried to follow what the documentation says, or the standards PSR. But, Mineiro, I don’t understand if you hate PHP or if you just think it’s bad even haha. In your opinion Python is good language for web applications? Should I migrate? Or just study PHP further to improve the way I use it?

  • "In another language it makes a lot of sense, but in PHP typing is still dynamic" Someday they will strengthen PHP typing?

  • 1

    ela só se torna um array quando eu executo um outro método probably error of design, but I can’t say without knowing the case.. I don’t hate any language, and I’ve used many, I like to study the subject, I’m not just a language user. I hate language fanaticism, either. PHP is one of the languages, which today, in the past was not so, has too many flaws. I’m not saying you should change your language. You’ll only change your problem. Nor should you continue with PHP. Don’t let people tell you what to do. Always study anything in depth...

  • 1

    ...only then you can make the right decisions on your own. Dynamic and weak typing are two completely different things, I put links about this, but I know that almost nobody clicks, people do not like to deepen their studies and if they learned wrong will be wrong forever. PHP cannot have strong typing without breaking all existing codes. Even static typing it may have but becomes more or less incompatible with the codes that use dynamic typing that is prevalent in almost all codes existing today.

  • Oh yes, I understand, I will see the links that you mentioned, I will study more deeply, if any doubt arises I comment here or open another question if it is the case.

  • @Uncle this, so it works.

Show 1 more comment

2

A contribution less complete than Maniero’s, but one that I believe should be taken into account. If you want to avoid unwanted trips to the database, you can use the infamous Singleton, I will not go into the details and discussions as to whether it should be avoided or not. Specifically in this case, let’s imagine a get method that will fill in and return the value of an attribute, as below:

private ?array $names = null;

public function getNames()
{
    if ($this->names === null) {
        $this->names = NamesDAO::retornaArrayAposConsultaOnerosa($this->outroAtributoQualquer);
    }

    return $this->names;
}

private ?array $names = null; makes sense, since this attribute being null simplifies the verification used in the method. If it were declared as private array $names = [];, The verification that access to the bank has already been made would not be so simple as NamesDAO::retornaArrayAposConsultaOnerosa($this->outroAtributoQualquer); always returns an array, which can be empty.

private array $names = []; is the most suitable option for other cases, as you will not need to keep checking if it is an array to make a foreach for example.

Browser other questions tagged

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