NYCPHP Meetup

NYPHP.org

[nycphp-talk] Optimal Object, property, variable passing strategy between classes

Mikko Rantalainen mikko.rantalainen at peda.net
Fri Jul 15 09:12:37 EDT 2005


csnyder wrote:
> On 7/14/05, Leila Lappin <damovand at yahoo.com> wrote:
> 
>>In C++ we used be able to declare a
>>parameter as constant and prevent it from being
>>modified.  I'm not sure if
>>'const'ness is possible in PHP.
> 
> 
> Oh yeah, check out define().
> 
> define( 'WEB_ROOT', '/var/www/html' );

And that would be (in C++)
const std::string WEB_ROOT("/var/ww/html");
(or something along those lines, I cannot remember)

Cliff Hirsch asked for PHP equivalent of following C++ code

void f(const type& param)
{
	/* do something with param, compiler generates an error
	   if param is modified in any way */
}

AFAIK, this isn't possible in PHP. I think that PHP implements 
copy-on-write for (at least) strings so if you don't pass complex 
objects, pass by value seems like a reasonable way (safe and fast).

I use objects as parameters for some methods and I do pass by 
reference because otherwise I'll end up with a copy (in PHP4). I 
also pass by reference if I have to pass an array.

So, I'd write above C++ code in PHP like this

function f(&$param)
{
	// try not to mess with $param ;-/
}

If I'm returning complex stuff like arrays or objects, I'll use

function &f(&$param)
{
	...
	return $a_complex_thing;
}

Again, there're cases where this can crash the PHP environment. (I 
think such a crash is always a bug. There have been some progress in 
PHP 4.4.0 on this area, if I've understood correctly.)

And no, you cannot emulate const'ness with a global variable. 
Passing a reference provides exactly the same safety and the same 
(almost?) performance.

-- 
Mikko



More information about the talk mailing list