44

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
}
Ali
  • 261,656
  • 265
  • 575
  • 769
  • 4
    I just noticed we are both 89 years old :O – code_burgar Oct 02 '09 at 23:39
  • I was never a php developer, but does this help: http://www.infoworld.com/article/2610885/facebook-q-a--hack-brings-static-typing-to-php-world.html ? – nawfal May 29 '15 at 18:15
  • PHP 7 is now STRICTLY typed (not STRONGLY typed). – RyanNerd May 31 '16 at 15:19
  • 2
    PHP won't ever (dare I say) become a strongly typed language, but I do believe that in the near future it will become a gradually typed language (like TypeScript).http://cstruter.com/blog/410 – cstruter Jun 29 '16 at 14:47
  • @RyanNerd What's the difference...? – Chuck Le Butt Jul 03 '17 at 16:59
  • 1
    Strongly typed languages such as C# forces you to declare a type for ANY variable you create (e.g. int my_integer, string my_string, object my_object). Strictly typed languages such as PHP enforce data types when activated such as via declare(strict_types=1). Also in PHP 7 strict typing exists only in your function parameters as type hints. In other words PHP 7 does not support this statement: string $myString = "string"; There was an RFC to add type declarations to properties in a class but sadly it got shot down: https://wiki.php.net/rfc/typed-properties – RyanNerd Jul 05 '17 at 19:10
  • you still can do $mystring = (String) 'Hello'; and $myInt = (Int) 120; .. but i hope to see these staff becoming necessary in the future – azjezz Dec 24 '17 at 07:53
  • Adding to @Antonin's 2015 answer (I'm not cool enough to comment yet), the official PHP 7 docs related to Return type declarations are here: http://php.net/manual/en/functions.returning-values.php#functions.returning-values.type-declaration This is a good place to start before you dive in: http://php.net/manual/en/migration70.new-features.php – Shadow Lynx Apr 26 '18 at 21:48

10 Answers10

66

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

Antonín Slejška
  • 1,980
  • 4
  • 29
  • 39
  • 7
    PHP7 still gives you zero errors/warnings on something as odd as `echo ('I want ' . ('$100' + 'dollars') . '!');` It will echo "I want 0!". So 1) don't write accounting software and critical systems in PHP if you can help it, 2) Don't expect PHP's type system to be up to par with Java, or even Python which throws exceptions on things like concatenating non-strings. – NoBugs Aug 17 '15 at 05:18
  • 3
    There is a difference between STRONGLY typed and STRICTLY typed as @NoBugs pointed out. PHP is moving in the direction of becoming a strongly typed language, but it is not quite there yet. – RyanNerd May 31 '16 at 15:17
  • 7
    @NoBugs: That code provokes a warning on PHP 7.1: https://wiki.php.net/rfc/invalid_strings_in_arithmetic – Janus Troelsen Aug 22 '16 at 11:20
  • 1
    I don't understand why the core team decided to implement it this way, but it's important to note that the strict mode declaration defines the **caller's** preference, and it's on a per-file bases. That is, any function/method **calls** made within the file respect the strictness setting for that file, including calls within the file that references methods/functions declared outside of the file. It does not apply to functions declared within the file (except when those functions are called from the same file they're declared). – Aaron Sep 15 '17 at 20:05
  • 2
    Also note that when a function is called in weak (non-strict) mode and an argument doesn't match the type declaration, the argument's value will be **coerced** to the declared type without warning. As the implementer, you have no control over this behavior, and if you wanted to actually enforce strict typing for a function for all cases, you would need to remove the type declarations and check types in the function definition manually. – Aaron Sep 15 '17 at 20:30
22

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.

Revious
  • 7,816
  • 31
  • 98
  • 147
code_burgar
  • 12,025
  • 4
  • 35
  • 53
  • 2
    In PHP 7 you can specify other types. See http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration – Barmar Jan 23 '17 at 01:08
  • 1
    Nope, this answer is outdated. PHP 7 does not allow this. It's only possible to declare types in function params. – boctulus Jan 18 '19 at 21:20
10

PHP is not strictly typed, so no. That said, it does support limited type hinting on functions - that's as close as it gets.

Alex Barrett
  • 16,175
  • 3
  • 52
  • 51
8

Unfortunately NO! I am at the end of a big project now that involves a lot alogorithms (graph theory, circuits etc) and I wish I hadn't choose php.

I have been using php for about 10 years, and still believe it is a good language, however one have to decide! What is bad for me, lack of strict typing might be good for someone else.

In addition, I want to mention, that I often wrote extra code for supporting strict typing, just a plain example is this:

if (is_array($r) && count($r)===0)

and the errors and hidden situations etc that were revealed are beyond explanation.

There were mistakes and situations that I would never been able to think/detect apriori, writing all these extra code was not enjoying but at least it will save me from silly mistakes!

If I would go back, maybe I would chose php for the web part, you know getting and showing data to the user, php is just great for that, handling string, arrays, talking to the database etc etc, but for the main core, algorithms etc I would go for C++, maybe haskell.. don't know, at least something strictly typed.

Melsi
  • 1,462
  • 1
  • 15
  • 21
  • 2
    I would avoid using the keyword 'and', as it may lead to unforeseen issues. Check out http://stackoverflow.com/questions/2803321/and-vs-as-operator#answer-2803576 – Tyzoid Jul 08 '13 at 19:12
  • @Tyzoid I cannot thank you enough for this, I program in php for years and never heard about that! I am editing my answer now. – Melsi Jul 10 '13 at 00:02
  • No problem :) I still learn things about php after five years. – Tyzoid Jul 10 '13 at 13:14
  • something I use that also enforces me to handle types is prefix nomenclature ... example: if I have an object Property that is Konstant and is of type Array, I would name it like this: pka_something; or if I have a Globally scoped Function I would name it like this: gf_something; or a Locally scoped Variable that is of type String: lvs_somestring ... ... the compiler doesn't see it, but it completely changed the way I write code – dsdsdsdsd Feb 04 '16 at 02:02
  • @dsdsdsdsd a naming convention won't stop you (or the consumers of your code) from causing type errors. Better delegate that job to your IDE by using phpdoc type annotations instead of an ugly non-standard naming convention. – rcd Apr 03 '18 at 16:35
3

Something you might try in order to simulate a poor man's strict type checking is using assert() to force the output to be of a particular type before you return it:

/**
 * Get Balance
 *
 * @return int
 */
function getBalance()
{
    /* blah blah blah */
   $out = 555; //Or any numeric value
   assert('is_int($out)');
   return $out;
}

So you keep your assertions active all throughout development and testing, sort of like the checks the compiler does at compile-time.

Granted, the assert() page is keen to assert that you shouldn't use assertions to check input parameters, but rather use normal conditionals to check them.

This answer had what I thought was a good rule:

The rule of thumb which is applicable across most languages (all that I vaguely know) is that an assert is used to assert that a condition is always true whereas an if is appropriate if it is conceivable that it will sometimes fail.

If you're simulating strict type-checking (writing your code to viciously maintain types; not trying to validate input from the outside), then you ought to be certain what the type is unless you've made a mistake.

Update:

There's also this: http://hacklang.org/ Facebook's PHP-based language with static typing.

Community
  • 1
  • 1
Calpau
  • 921
  • 10
  • 21
3

Perhaps you should try this PHP extension https://github.com/krakjoe/strict. Support for the following types is introduced:

  • string
  • integer, int
  • float, double
  • boolean, bool
  • resource
marcio
  • 10,002
  • 11
  • 54
  • 83
  • 3
    Support is only introduced for parameter types, and eventually return types (when patch is merged into PHP7). Typed variables are not possible via an extension. – Joe Watkins Dec 06 '14 at 08:26
3

You could use h2tp transpiler to transpile HACK code to PHP:

You can do this thanks to Facebook Team and HACK Language.

Visit http://hacklang.org and http://hhvm.com for more info.

If you want to code directly in Hack + HHVM environment you can also use Facebook's internal IDE Nuclide

JavierFuentes
  • 1,840
  • 18
  • 13
2

Since the answer is basically "no", an alternative: A PHP "linter", which should catch some of the things a compile-time check would catch in a staticly-typed language like C. Not the same, but should prevent some sillyness

"Is there a static code analyzer [like Lint] for PHP files" lists many of these.

Community
  • 1
  • 1
dbr
  • 165,801
  • 69
  • 278
  • 343
2

PHP 7.0 introduced function return type hints, and PHP 7.4 added support for class property type hints. As of PHP 7.4, your code would be:

<?php declare(strict_types=1);

class MyObject
{
}

class TypedStuff
{
  public static int $x;
  public static string $y;
  public static bool $z;
  public static MyObject $foo;
}

function getBalance(): float
{
  return 555; //Or any numeric value
}

TypedStuff::$x = 6;
TypedStuff::$y = "hello world";
TypedStuff::$z = false;
TypedStuff::$foo = new MyObject();

You can't type-hint one-off variables, but you can type-hint static class properties, which could be used in an almost identical manner. You can also type-hint the return type of stand-alone functions.

More commonly, you'd be defining typed values inside a class using a typed setter, and receiving typed values outside a class using a typed getter, like:

<?php declare(strict_types=1);

class Person {
  private $age;

  public function __construct(int $age)
  {
    $this->age = $age;
  }

  public function setAge(int $age): void { $this->age = $age; }
  public function getAge(): int { return $this->age; }
}

$person = new Person(30);
echo sprintf(
  'The person is %d years old.',
  $person->getAge()
);

This works in PHP 7.0 because property type-hints are not required.

Zeal
  • 474
  • 3
  • 4
1

No. That syntax will not work.

You could, theoretically, come up with a system of objects that enforced their own sort of strict typing, but it wouldn't perform and ...why would you want to, anyway?

If you need strict typing, use a strictly typed language.

Frank Farmer
  • 38,246
  • 12
  • 71
  • 89
  • I would love to use a strictly typed language but my clients only want to use php :( – Ali Oct 02 '09 at 23:39
  • 1
    Thank your clients ... or curse them ... as the case may be. – pavium Oct 02 '09 at 23:47
  • 3
    If a strictly typed language is really the only right tool for the job, you might consider pushing back. If you hired a carpenter, you wouldn't tell him to use only a screwdriver. – Frank Farmer Oct 02 '09 at 23:53
  • 1
    Yep, but web development jobs for java appear to be scarce compared with PHP, also the infrastructure for java web apps is a bit more complex/expensive than a LAMP shared hosting.. – Ali Oct 03 '09 at 00:34