Strict types

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hi All,

For a while now I've been wishing PHP had (at least the option to
enable) strict types. It would help a massive amount in BIG
applications, and maybe start to taper the millions of lines of crap
code that's out there.

PHP is a great language, but the masses of incompetant coders out there
do absolutely nothing to help the language grow. I know we all have to
start somewhere, so please don't think I'm being eliteist, because I'm
not, but something has to be done to try to fix the mess out there.

Surely the contractors on here have witnessed this, or is it just me?

What is everyone else's opinion?



Re: Strict types

On Thu, 30 Mar 2006 00:53:47 -0800, Treefrog wrote:
Quoted text here. Click to load it

To be honest the only real problem is with objects.  For large
applications a consistent naming scheme helps with simple variables and in
a lot of cases it's not really important what the variable is.

With regards to objects, PHP5 now has type hints which ensures a parameter
to a function or method is of a given type (class):

function bar(Foo $foo)



Andy Jeffries MBCS CITP ZCE   | gPHPEdit Lead Developer | PHP editor for Gnome 2 | Personal site and photos

Re: Strict types

Treefrog wrote:
Quoted text here. Click to load it
Well, you could do it in PHP5 by wrapping all the basic types in classes  
like java does for a lot of things. Then each type class would have its  
own toXXX converters to handle the casts.

This is an example of 'fixed with another level of abstraction' and I  
wonder at the utility of it all. PHP - like shell - is often attractive  
to coders *because* it is loosely typed.

I'm not sure how many coders would find PHP as attractive if they had to  
follow stricter object type coding. For example:

$a = 'This is a string';
$b = ' This is another string ';
$c = 3;
$d = $a.$b.$c;

would become something like:
$a = new String('This is a string');
$b = new String(' This is another string ');
$c = new Int(3);

$d = $a->concat($b->concat($c->toString()));

Type-safe - sure! More meaningful? I would argue that all the method  
calls get in the way of the meaning of the code.

Wasn't there a phplint project to help do some high level analysis of code?


Re: Strict types

David Haynes said the following on 30/03/2006 11:43:
  > I'm not sure how many coders would find PHP as attractive if they  
had to
Quoted text here. Click to load it

Well, Java has strict typing, and you don't have to do this.  Same in  
C++ (for the most part).


Re: Strict types

Oli Filth wrote:
Quoted text here. Click to load it
Yes, they do, but they are designed into the language from the  
beginning. I was operating from the assumption of using what was  
available today in PHP5.


Re: Strict types

David Haynes wrote:
Quoted text here. Click to load it

Cute. I might spend some time playing with that idea. but I'd prefer if
PHP had built in support...

Quoted text here. Click to load it

Hmm, I agree I think, hence wanting the option to use strict types. The
problem is, from my experience, people initially use PHP because it's
easy and they can get their idea realised in a short time with a
minimal leanring curve/expense. Unfortunately, soem of these ideas
actually work and start making money, sometimes BIG money, and they are
left with poorley coded legacy crap that everybody firefights to keep
working... and any improvments are complete kluges.

I'm not sure what can be done to change that, but I want to stay with
PHP, it can be used for huge scalable systems, but only if coded
properly. I suppose I'm clutching at straws to make it harder to write
bad code.

Re: Strict types

Treefrog wrote:
Quoted text here. Click to load it

I think it ends up being more organic. You start to develop a set of  
libraries and practices that protect you from a lot of coding goofs and  
continue to build/refine.

One of the more humbling things I think any good coder can do is look at  
their code from a year or two before. I know I usually end up wondering  
what I was thinking in some places ;-)

With the stronger object support in PHP5, a lot of things can be coded  
to be protected well and, as with all programming languages, it is  
possible to write good and bad code regardless of the protection the  
language offers.

One other way people have handled the 'type' issue is to use a strong  
naming convention - e.g. Hungarian notation. Personally, I can't stand  
using it but others find it helpful.


Re: Strict types

Treefrog wrote:
Quoted text here. Click to load it

Hi, T'rog,

Well, one of the big attractions to PHP is the lack of strict typing.  You don't  
have to go through all the overhead of declaring variable types (or even  
variables unless they are class members).  Getting rid of the "administrative  
overhead" allows you to concentrate on the problem.

You can write good code in any language (except maybe COBOL :-) ).  You can  
write bad code in any language - including Java and C++.  However, IMHO, strict  
typing does in general get you to write "better" code.

I think a good compromise between old and new would be a "strict" flag.  It  
could be set in the php.ini file or .htaccess (on Apache, if allowed).  Perhaps  
it could even be a parse-time command (ini_set isn't executed until too late),  
similar to C/C++'s pragma statement.  The last would allow someone to convert a  
website one file at a time to strict.  Then when everything's changed, change  
the php.ini file, or, if on a shared server, at a statement to .htaccess.

Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.

Re: Strict types

Treefrog wrote:
Quoted text here. Click to load it

Generally speaking, PHP is a scripting language. Scripting languages are  
great for one-off projects and small programs, but become unwieldy in  
big applications, larger than a few thousand lines. For larger projects,  
I would suggest Java, which has strict typing and encourages  
object-oriented programming and modularization.

Re: Strict types

Steve Chapel wrote:
Quoted text here. Click to load it

No no, I can already code c# (so probably Java too), that has strict
types and great oo support, but I've grown up using PHP, all my
professional career has been mainly PHP based and I want to stay with
the language. I've seen it evolve to inlcude basic OO support, then
more advanced OO....

Once upon a time, PHP was a scriting language, but it's more than that
now. For example, I'm currently working with a 500,000 line 100% PHP
application. Because 95% of it is built on poor coding, it's nearly
impossible, certainly futile to try to impliment standards into it. I
was just trying to think of/ask for ways in which situations like this
can be stopped in the future. Which, I think needs to happen for PHP's
future. I've worked in quite a few places, and with quite a few other
developers, and they seem to agree; PHP code is nearly always messy

But it doesn't have to be.

Re: Strict types

Treefrog wrote:
Quoted text here. Click to load it

I'm not so sure about that. Large Perl programs (and even many small  
programs) are nearly always messy crap. I believe it's a natural  
property of languages that have weak or loose typing, do not require you  
to declare variables, and do not have a separate compilation step. These  
kinds of languages are often called scripting languages  
< .

Perhaps there is a way to make scripting languages more suited for large  
applications. Discussion of how to do that may be beyond the scope of a  
post in a PHP newsgroup, however.

Re: Strict types

Treefrog wrote:
Quoted text here. Click to load it

Eliminating badcode by altering the language--that sounds rather
Orwellian to me.

Re: Strict types

Chung Leong wrote:
Quoted text here. Click to load it
You mean double plus ungood?

Re: Strict types

Chung Leong wrote:
Quoted text here. Click to load it

You're absolutely right. My most humble apologese. Let the bad code

Re: Strict types

Treefrog wrote:
Quoted text here. Click to load it

Just because people can make illogical statements in English does not
imply that stupidity will prevail.

Re: Strict types

Chung Leong wrote:

Quoted text here. Click to load it

Au contraire, mon ami!

Re: Strict types

Quoted text here. Click to load it

Starting from the same thought, I realized that a scripting language has
the nice property to allows for fast code development of little programs,
like most the simpler WEB pages indeed are. That's way PHP is so popular.

Faced with the perspective to switch to another strong-typed language
in order to develop some complex applications, I discovered another
development pattern, that is: write your messy code, then check it with
a formal validator.

Problem: no PHP formal validators seem to be available. That's way
I wrote PHPLint, a formal validator for PHP4 and PHP5. It takes your
sources and spots errors and potential problems, like:

unused constants/variables/functions/classes/properties/methods (for
short: "items");

type mismatch in items usage (you can't add a string to a number without
an explicit typecast);

type mismatch in function arguments (you can't pass a string to a function
requiring an array, for example);

all the properties of a class must be declared; their type given by the
initial value or specified through PHPLint meta-code.

This sample of code should give an idea. The comments summaryze the complains
of the validator:


class Example {
   private $aString = "something";   # inferred type: string
   public /*. int .*/ $anInt;
   public $xxx = 0;

   public function __construct(/*. string .*/ $s, $i=0)
   { $this->aString = $s;    $this->anInt = $i; }
   # inferred method signature: void(string [, int])

   public function getString()
   { return $this->aString; }
   # inferred method signature: string()

$obj = new Example("hello");
# inferred var. type: class Example

$obj->aString = "";   # <-- ERROR: accessing private property

$obj->gggg = 999;   # <-- ERROR: no property gggg in class Example

$obj2 = new Example(123);  # <-- ERROR: expected arg of type string

$num = 3;
# inferred var. type: int

$num = $obj;   # <-- ERROR: type mismatch in assignment
$num += (int) $obj->getString();
$num += $obj->getString();  # <-- ERROR: type mismatch

if( $num === 0 ) { $num = 1; }  # ok
if( $num ) { }   # <-- ERROR: invalid bool expr

$fp = fopen("data1.txt", "r");
if( $fp === FALSE )
   die("can't open data.txt");

$fp = fopen("data2.txt", "r") || die("xxx");  # ERROR: invalid expr


# notice: the property `anInt' used only inside its class, you should make it `private'
# unused property `Example::$xxx'

/_|_\  Umberto Salsi

Site Timeline