Custom typing

Asked

Viewed 109 times

3

According to the DOC Type handling, the conversions allowed are:

(int), (integer)          - molde para inteiro
(bool), (boolean)         - converte para booleano
(float), (double), (real) - converte para número de ponto flutuante
(string)                  - converte para string
(array)                   - converte para array
(object)                  - converte para objeto
(unset)                   - converte para NULL (PHP 5)

I wanted to know if there is any way to create a custom typing. I searched in the documentation and SO-EN but found nothing related to this.

I already have a function for that purpose, but I wanted to create a type (upper) 'Papa Chalie' // PAPA CHARLIE, would be possible?

  • 1

    I do not think possible, http://php.net/manual/en/function.settype.php . " Possibles values of type are: ..." . There you can see the possible types

2 answers

5


PHP does not have cast for real. It has functions that convert values. Remember that PHP is dynamically typed, so the type of the variable does not matter and the cast serves to reconcile a value with a variable.

To convert values serves any function. You will not have the syntax of cast, but it is a good thing to make it clear that this is a conversion. Then create a function that interprets the values of the received object and creates a new object within the possibility of it. This function can be dropped or it can be inside a class, it can be static or instance.

Actually the example given if it could be used would be a complete abuse of the syntax since it even changes the type.

Behold how it works in C# to get an idea how this operator in the background is a function that allows an appropriate syntax when it is a coercion of type. PHP doesn’t have it.

  • Yes, the example does not change the type, it continues as a string, but taking into account that 'a' === 'A' is false, I judged the existence of a typing upper and Lower.

  • 1

    It makes no sense. 'a' === 'A' is like comparing 1 === 2; in both cases, you are comparing equal types with different values.

4

Is not possible.

Note further that the cast or data conversion is used to turn one data type into another. What you are trying to do is turn the 'format' or value of a variable (string) to high box, and the path is to use a function.

There is no need to implement a function to do this, there are native php functions strtoupper, mb_strtoupper.

In response to 'a' === 'A' is false: I will try to answer in a very informal, non-technical way. It is because they are different values, note that the operator === checks by type and value, and 'a' is different from 'A' as much as 'b'. Internally, each letter has a number value, note the value of 'a' has to be different from 'b', 'c', and also from 'A', so that we can print, compare, etc., instead of each other.

Browser other questions tagged

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