Class Efficentcy

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
baileylo
Forum Newbie
Posts: 13
Joined: Sun Sep 30, 2007 12:48 am

Class Efficentcy

Post by baileylo »

[I'm writing a class and I was wondering if it was:
better to define the specific class that the variable will be like this

Code: Select all

$this->author = new user();
making sure the correct space is set aside because it will be needed later anyways. And say something is going to be an array and it is define as such:

Code: Select all

$this->friends = array();
is there a way for me to set it so that it knows that the friends array is of type user?

or if i should i just define it as:

Code: Select all

$this->author = null;
$this->friends = null;
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Class Efficentcy

Post by superdezign »

baileylo wrote:is there a way for me to set it so that it knows that the friends array is of type user?
PHP is very loosely typed, so there's no way for you to restrict that variable's type. Luckily, with PHP 5, you can control the access to member variables, so you can ensure that it is the type that you want it to be with accessor methods.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Re: Class Efficentcy

Post by Chris Corbyn »

baileylo wrote:is there a way for me to set it so that it knows that the friends array is of type user?
I wish this were doable. I've recently had to create MyTypeSet classes (i.e. HeaderSet, UserSet etc) for situations where I need to know what the type is. in PHP5's SPL library there is a ArrayObject interface which allows you to treat the object (almost) like an array though.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Class Efficentcy

Post by Weirdan »

Chris Corbyn wrote: I wish this were doable.
I believe there's an extension in pecl for this... yes, here it is: http://pecl.php.net/package/SPL_Types
Post Reply