Jump to content

private class properties


NeverToOld

Recommended Posts

Hi guys

 

what I am trying to do is create class properties with a foreach loop.

   function __construct($row) {
                
            foreach( $row as $key => $value )
                     $this -> $key = $value ;
            
        }

 

$row is a associate array from mysql.

 

I have the properties created and values applied but was wondering how to make them private.

 

Thanks in advance

 

 

Link to comment
https://forums.phpfreaks.com/topic/265536-private-class-properties/
Share on other sites

AFAIK you can't.  Dynamically created object members default to public.  Why?  Any members that don't have an access modifier (one of public, protected, or private) default to public.  Since you can't create an access modifier dynamically, they'll be un-labeled, and thus public.

 

More to the point, what are you trying to do?  In most cases, objects are defined upfront, with their fields declared.

<?php

$arr = array(
'foo'=>'bar',
'cas'=>'bah'
);

$obj = new fancyclass($arr);

$obj->useIt();

class fancyclass {

private $data = array();

public function __construct($row) {
	$this->data = $row;
}

public function useIt() {
	foreach( $this->data as $key => $val ) {
		echo "$key => $val<br>";
	}
}

}

?>

Hi Kevin, thanks for the reply.

 

I'm doing it for a generic user/person type class.

 

I originally put all the properties in by hand as private but this tied me to the one website I am learning oop with, I would like it to be reusable with any associate array.

 

I'm not sure, I don't remember seeing it directly, but at the same time I was never really looking for it.

 

It's just kinda general knowledge. Extracting data out of an array is kind of redundant. Keep it as an array :D

 

Also, dynamically creating properties can be dangerous, unless the class is anonymous or built entirely around having dynamic properties (no predefined ones that might be overwritten)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.