473,320 Members | 1,990 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Type safety in PHP

If I have a function that expects first argument to be of type (class
foo) and second argument to be of type class foobar,how do I check/
ensure that I have been passed the right parameter types?

In C++, it would be done something luike this:

void Func(const foo& foo_objectRef, const foobar& foobar_objectRef)

How can I enforce the requirement that only these data types can be
passed to the function Func above?

Since PHP is loosely typed, I suspect that there is no way of enforcing
this kind of type integrity, - so in case I can't enforce this - how can
I atleast check that I have not been passed a string (for example), when
I am expecting an object of type foo or foobar?
Jun 2 '08 #1
4 3566
On Sat, 03 May 2008 16:37:40 +0200, Ronald Raygun <in*****@domain.com
wrote:
If I have a function that expects first argument to be of type (class
foo) and second argument to be of type class foobar,how do I check/
ensure that I have been passed the right parameter types?

In C++, it would be done something luike this:

void Func(const foo& foo_objectRef, const foobar& foobar_objectRef)

How can I enforce the requirement that only these data types can be
passed to the function Func above?

Since PHP is loosely typed, I suspect that there is no way of enforcing
this kind of type integrity, - so in case I can't enforce this - how can
I atleast check that I have not been passed a string (for example), when
I am expecting an object of type foo or foobar?
Since PHP5 you can require a certain kind of object (or an array):

<?php
//Classes
class Foo {
function bar(Foo $foo, Foobar $foo = null){
echo "Works\n";
}
}
class Bar extends Foo{}
interface Foobar{}
class Foz implements Foobar{}
class Baz{}

//Errors to exceptions
function _error_handler($errno,$errstr){
if($errno & error_reporting()) throw new Exception($errstr);
return true;
}
set_error_handler('_error_handler');

//Illustration
$foo = new Foo();

try{$foo->bar(new Foo());}
catch (Exception $e){ echo "Doesn't work.\n";}

try{$foo->bar(new Bar());}
catch (Exception $e){ echo "Doesn't work.\n";}

try{$foo->bar(new Baz());}
catch (Exception $e){ echo "Doesn't work.\n";}

try{$foo->bar(new Foo(),new Foz());}
catch (Exception $e){ echo "Doesn't work.\n";}

try{$foo->bar(new Foo(),null);}
catch (Exception $e){ echo "Doesn't work.\n";}

try{$foo->bar(new Foo(),new Baz());}
catch (Exception $e){ echo "Doesn't work.\n";}
?>
Result:

Works
Works
Doesn't work.
Works
Works
Doesn't work.

Manual:
http://nl2.php.net/manual/en/languag...ypehinting.php
--
Rik Wasmus
Jun 2 '08 #2


Rik Wasmus wrote:
On Sat, 03 May 2008 16:37:40 +0200, Ronald Raygun <in*****@domain.com>
wrote:
>If I have a function that expects first argument to be of type (class
foo) and second argument to be of type class foobar,how do I check/
ensure that I have been passed the right parameter types?

In C++, it would be done something luike this:

void Func(const foo& foo_objectRef, const foobar& foobar_objectRef)

How can I enforce the requirement that only these data types can be
passed to the function Func above?

Since PHP is loosely typed, I suspect that there is no way of
enforcing this kind of type integrity, - so in case I can't enforce
this - how can I atleast check that I have not been passed a string
(for example), when I am expecting an object of type foo or foobar?


Since PHP5 you can require a certain kind of object (or an array):

<?php
//Classes
class Foo {
function bar(Foo $foo, Foobar $foo = null){
echo "Works\n";
}
}
class Bar extends Foo{}
interface Foobar{}
class Foz implements Foobar{}
class Baz{}

//Errors to exceptions
function _error_handler($errno,$errstr){
if($errno & error_reporting()) throw new Exception($errstr);
return true;
}
set_error_handler('_error_handler');

//Illustration
$foo = new Foo();

try{$foo->bar(new Foo());}
catch (Exception $e){ echo "Doesn't work.\n";}

try{$foo->bar(new Bar());}
catch (Exception $e){ echo "Doesn't work.\n";}

try{$foo->bar(new Baz());}
catch (Exception $e){ echo "Doesn't work.\n";}

try{$foo->bar(new Foo(),new Foz());}
catch (Exception $e){ echo "Doesn't work.\n";}

try{$foo->bar(new Foo(),null);}
catch (Exception $e){ echo "Doesn't work.\n";}

try{$foo->bar(new Foo(),new Baz());}
catch (Exception $e){ echo "Doesn't work.\n";}
?>
Result:

Works
Works
Doesn't work.
Works
Works
Doesn't work.

Manual:
http://nl2.php.net/manual/en/languag...ypehinting.php
Thanks for the clarification!
Jun 2 '08 #3
On May 3, 3:37*pm, Ronald Raygun <inva...@domain.comwrote:
If I have a function that expects first argument to be of type (class
foo) and second argument to be of type class foobar,how do I check/
ensure that I have been passed the right parameter types?

In C++, it would be done something luike this:

void Func(const foo& foo_objectRef, const foobar& foobar_objectRef)

How can I enforce the requirement that only these data types can be
passed to the function Func above?

Since PHP is loosely typed, I suspect that there is no way of enforcing
this kind of type integrity, - so in case I can't enforce this - how can
I atleast check that I have not been passed a string (for example), when
I am expecting an object of type foo or foobar?
PHP 4 would require to use gettype (), get_class () and/or is_a ()
inside your function to verify the type of the item passed to your
function.

PHP 5 would still require a gettype () for language primitives, but
for objects and arrays you can use type hinting to restrict the type
of argument passed to your function. For example if you want your
function to only work on PDO objects you could do something like:

function doSomethingWithPdo (PDO $item)

An error will be raised if you try passing it something that isn't a
PDO object.

You can also use type hinting with interfaces, which is really useful
if you want a function that will operate on a range of different
classes in a uniform way.

interface DoesSomething
{
...
}

class A implements DoesSomething
{
}
class B implements DoesSomething
{
}
class C
{
}

function doSomething (DoesSomething $item)

You can use doSomething with items of class A or B, but trying to use
it with an item of class C will raise an error.
Jun 2 '08 #4
Ronald Raygun wrote:
....
>Manual:
http://nl2.php.net/manual/en/languag...ypehinting.php

Thanks for the clarification!
And you can write you own class to check primitive types. Examples of
using:

<code>
....
/// Get nested node by name attribute
/**
* @param $node parent node
* @param $name name attribute value
* @return target node or null if not found
*/
function getByName($node,$name)
{
chk::args('DOMElement',A_STRING);

....
/// Get existing in game child objects
/**
* @param $parentId parent object id or object itself
* @param $classId class id or class name
* @return game object
*/
function getChilds($parentId,$classId)
{
chk::args(A_INT|A_OBJECT,A_INT|A_STRING);
....
</code>

debug_backtrace() used in chk::args() ?? check arguments and make good
error message.

I hope in future they will add type hinting for all cases.
Jun 2 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Steve Jorgensen | last post by:
I frequently find myself wanting to use class abstraction in VB/VBA code, and frankly, with the tacked-on class support in VB/VBA, there are some problems with trying to do that and have any...
2
by: Dave | last post by:
Hello all, I am creating a linked list implementation which will be used in a number of contexts. As a result, I am defining its value node as type (void *). I hope to pass something in to its...
18
by: aarklon | last post by:
In the article http://en.wikipedia.org/wiki/Type_safety it is written as The archetypal type-unsafe language is C because (for example) it is possible for an integer to be viewed as a function...
27
by: Noah Roberts | last post by:
What steps do people take to make sure that when dealing with C API callback functions that you do the appropriate reinterpret_cast<>? For instance, today I ran into a situation in which the wrong...
21
by: Chad | last post by:
Okay, so like recently the whole idea of using a Union in C finally sunk into my skull. Seriously, I think it probably took me 2 years to catch on what a Union really is. Belated, I mentioned this...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.