Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write strictly typed PHP code?

Tags:

oop

php

For example, is it possible to write code like this:

int $x = 6; str $y = "hello world"; bool $z = false; MyObject $foo = new MyObject(); 

And is it possible to define functions like this:

public int function getBalance() {    return 555; //Or any numeric value } 
like image 454
Ali Avatar asked Oct 02 '09 23:10

Ali


People also ask

Is PHP typed or untyped?

While working with these programming scripts, you need to use a sign for each variable type(like string, integer, float, etc.) to declare them. You just need to assign a string value to the variable, to define that our variable is an integer. This is the reason why PHP is a loosely typed language.

What kind of typing does PHP use?

Because PHP checks the type of variables at runtime, it is often described as a dynamically typed language. A statically typed language on the other hand, will have all its type checks done before the code is executed.

Is Python strongly typed?

Python is both a strongly typed and a dynamically typed language. Strong typing means that variables do have a type and that the type matters when performing operations on a variable. Dynamic typing means that the type of the variable is determined only during runtime.

Is C statically typed language?

A statically-typed language is a language (such as Java, C, or C++) where variable types are known at compile time.


2 Answers

In PHP 7 are implemented "Scalar Type Declarations", e.g.:

public function getBalance(): int {     return 555; } 

You need to declare, that you will use strict types:

<?php     declare(strict_types=1);      function sum(int $a, int $b): int {         return $a + $b;     }      sum(1, 2); ?> 

More information: https://wiki.php.net/rfc/scalar_type_hints_v5

like image 51
Antonín Slejška Avatar answered Oct 11 '22 19:10

Antonín Slejška


Edit: This answer applies to versions of PHP 5.6 and earlier. As noted in recent answers, PHP version 7.0 and later does have some support for this


Original answer:

No. There is only support for type hinting since php5, but "Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported."

In PHP 7 are implemented "Scalar Type Declarations" see the answer below.

That is as far as php currently goes, and as far as it should go if you ask me.

like image 43
code_burgar Avatar answered Oct 11 '22 18:10

code_burgar