Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 378
  • Last Modified:

PHP oop goodness :-)

Hi there,

Just getting my hands on some PHP5 oop goodness...
now just writing up a class that will handle a user.

now I can do
class user
{
      
  private $id   = -1;
  private $fname = '';
  ......

then do a function load_user($id)
select user from database and use mysql_fetch_assoc
like
$user_data = mysql_fetch_assoc($result);
Foreach ($user_data AS $key->$var)
  $this->$key = $var;

however, what happens if I don't want to declear all those private vars at the start of the class...
can I do
Foreach ($user_data AS $key->$var)
  private($this->$key = $var);
or some other way of telling PHP5 that this new var is to be private. Because by default it's public.

Just trying to make it as clean cut and readable as possible....

0
wildzero
Asked:
wildzero
2 Solutions
 
dragonccCommented:
Every programming book I've read advocates declaring all your vars at the beginning, making them private, and giving access to vars only via getters & setters. I declare any properties at the beginning of the class, but it doesn't necessarily matter where you declare them, that's your preference. The only thing you can't do is use the private declaration as if it were a  function ie "private($this->key = $var)" you'd have to separate that out, declare the var first, then assign the value to it.
 
I don't know if you just typed that code up real quick or if it's actually in use, but a couple things to watch out for:
when using $this->somevar, you don't put a $ in front of the var name your referencing.  Also when using foreach, you should have to use => in the statement instead of ->, I know my debugger errors out if I type it that way.

Hopefully that helps.
0
 
hernst42Commented:
If you want "generic" private attributes, why not store all those attributes in an private array like:

class user
{
      private $_data = array();

Then assign the $user_data to $_data

$this->_data = $user_data;

access the attributes with $this->_data['id'] instead of $this->id

defining attributes of a class on the fly makes no real sense in terms of OOP.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now