473,624 Members | 2,069 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

type hint method/function return value

guillermobytes
77 New Member
Hi,
I was wondering if there is a way (from an interface or abstract class) to force all classes implementing some method to return a specific type, like in Java.

example :
Expand|Select|Wrap|Line Numbers
  1. //method can only return strings
  2. public function string someMethodName();
  3. //method can only return PDOStatement instances
  4. public function PDOStatement prepare();
  5.  
thank you for your help!
Sep 8 '10 #1
6 3291
Markus
6,050 Recognized Expert Expert
Nope, not currently, although there is are RFCs on the matter. My views on this feature are undecided yet.
Sep 11 '10 #2
guillermobytes
77 New Member
thanks a lot markus!
well I don't know if this will be very expensive in efficiency, but for coding, I find it easier to explicitly tell in an interface what a method should return, than in documentation or even in the piece of code (where the method is supposed to be called).
Anyways I'm not an advanced programmer but that's how i feel about it.
Sep 11 '10 #3
Dormilich
8,658 Recognized Expert Moderator Expert
the big problem is, PHP is a loosely typed language. forcing an return type completely defeats that concept.
Sep 12 '10 #4
guillermobytes
77 New Member
yes good point,
however if I find loose types very useful when you declare variables, with functions I don't. It is very helpful to be able to force some type of return in interfaces/abstract classes... this allows to create frameworks where the end developer directly knows what he can do and what he cannot.
It also reduces the amount of code, because there is no need to make type checks for each method of some interface implementation, just check that the instance is of type <Interface> and you are sure that all return types will be correct:
Expand|Select|Wrap|Line Numbers
  1. Interface PDOStatement_Interface 
  2. {
  3. public function bool bindColumn ( mixed $column , mixed &$param [, public function int $type [, int $maxlen [, mixed $driverdata ]]] )
  4. public function bool bindParam ( mixed $parameter , mixed &$variable [, int $data_type = PDO::PARAM_STR [, int $length [, mixed $driver_options ]]] )
  5. public function bool bindValue ( mixed $parameter , mixed $value [, int $data_type = PDO::PARAM_STR ] )
  6. public function bool closeCursor ( void )
  7. public function int columnCount ( void )
  8. //...
  9. Class Foo
  10. {
  11.   static public $adapterClassName = 'SomeAdapterClass';
  12.   static public function getPDOStatementAdapter()
  13.   {
  14.     $adapter = new self::$adapterClassName();
  15.     if ($adapter instanceof PDOStatement_Interface) {
  16.       throw new Exception('Your adapter does not implement interface
  17.       thus it will crash when i'll try to use methods that don\'t exist or that
  18.       don\'t return the value that i need');
  19.     }
  20.     return $adapter;
  21.   }
  22. }
  23.  
In my example if the interface can't check the return types, then when using the adapter methods, one should check that the return type is what it is expected, which could result in 30 methods, used in 50 different places => 30*50 = 1500 if statements:
Expand|Select|Wrap|Line Numbers
  1. //here we asume PHP has not type hinting
  2. $res = Foo::getPDOStatementAdapter()->bindColumn(/*...*/);
  3. if (!is_bool($res)) {
  4.   throw new Exception('Sorry the return type of your adapter is not supported!');
  5. }
that's the main reason i like type hinting in methods.
but for those who don't need it the php developers would probably(almost 100% sure) allow two types of usage : the old fashion:
Expand|Select|Wrap|Line Numbers
  1. publid function someMethod();
and the new one :
Expand|Select|Wrap|Line Numbers
  1. public function string someMethod();
Sep 12 '10 #5
Dormilich
8,658 Recognized Expert Moderator Expert
more arguments against return types:
- how to implement (on the PHP side)? if you return a variable, it could have any type, and not every type can be converted into any other type. (it might not be a huge problem with String, but with object/interface)
- new coders will fail to grasp the concept
- you need a pre-compiler
- incompatibility with old scripts
Sep 13 '10 #6
guillermobytes
77 New Member
I don't understand what you mean when you say : "- how to implement (on the PHP side)? if you return a variable, it could have any type, and not every type can be converted into any other type. (it might not be a huge problem with String, but with object/interface)"
why should you convert to another type than the one returned? the purpose of restricting the return type, is to make the script crash when the return type is not the one expected.

you are right on the second point, and it is important because php has a huge percentage of new coders. but probably the people at php will allow the old fashion use, that's why I don't think that (if ever implemented) it will be incompatible with old scripts.

for the pre-compiler you are probably right again, but wouldn't it also be possible to make the return type check on execution? that would limit the return type checks to the methods that get executed, which isn't as great as with a pre-compiler. Now i think that the greatest thing would be to use both :
-a runtime check and
-a pre-compile check
when in development, you could activate the pre-compile check with an ini_set('pre-compiler', 'on').
Then when you go to production you disable it and the checks are only made when the methods get executed.
Sep 13 '10 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

3
3440
by: Jonas | last post by:
Dear members, How can I use a function return value in a regexpr? $tmp=~s/mysearch/myfunction($1)/; sub myfunction { return $v; }
1
2616
by: Tropos | last post by:
Query: Will a MutexGuard object release before a function return value is copied? Consider the C++ code: class MutexGuard //A familiar sort of class for making mutexes exception-safe { . . . ~MutexGuard(); //releases the mutex when the stack pops
7
1948
by: Michael Klatt | last post by:
class Foo { public : explicit Foo(int i) : m_int(i) {} private : int m_int; }; Foo f(int i)
4
4284
by: wongjoekmeu | last post by:
Hello All, I know that when you pass an argument to a function (if you want let the function be able to change the value) then you can choose to pass the argument by reference or a pointer to that argument. Now my question is, why would you prefer to let a function return a reference or a pointer ??? Consider the following with operator overloading. I suppose the operator can be seen as a function (right ?)
5
4220
by: Ghislain Tanguay | last post by:
Hi! I'm maybe from old school but, for me, whebn it's time to call a method from DCOM, remoting or web service returning a string or anything else I use a function. It's more verbose. In my new company, much of my coworker works with Public sub ( byval Itemx as integer, byref returnCode as Integer). I don't understand why they use this kind of sub and i'm wondering if this kind of sub take more time to response?
11
2762
by: randomtalk | last post by:
hi, i have the following recursive function (simplified to demonstrate the problem): >>> def reTest(bool): .... result = .... if not bool: .... reTest(True) .... else: .... print "YAHHH" .... result =
8
2054
by: bdobby | last post by:
Hi. I am relatively new to js, but I did think I was starting to get the hang of it. Then this happened... I have a form with an onsubmit event handler: <form id="uploadForm" method="post" action="..." onSubmit="checkDates()"> The event handler does some minor validation, then returns true or
10
1351
by: =?Utf-8?B?bGlhbnF0bGl0?= | last post by:
In performance wise which is more costly to use when there one value to return? Is it the out method parameter or the method that has a return value?
4
1648
by: pradeep | last post by:
Hello friends ~ We know that a C function will return a 32-bit value from a function in %eax and a 64-bit value in %edx:%eax. But what about larger return types, for example large structs? The only other spare register is %ecx because %ebx needs to be preserved, but that only brings the %possible total up to 96 bits. What happens after that? Thanks for any information!
6
18988
by: kurt.krueckeberg | last post by:
Can someone explain why this line $bool = isset($_POST) && !empty(trim($_POST)); causes the error message "Can't use function return value in write context". trim() returns a string. I test if it is empty. So what is wrong with that?
0
8238
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8174
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8680
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8624
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8336
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6111
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5565
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4082
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1786
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.