PHP - Setting Deep Object Properties
I need to set a deep property if it is undefined or NULL such as shown below: function setProperty($value, stdClass $config, $p1, $p2, $p3, $p4) { if(!isset($config->$p1->$p2->$p3->$p4) || is_null($config->$p1->$p2->$p3->$p4)) { $config->$p1->$p2->$p3->$p4=$value; } } $config=json_decode(json_encode(['a'=>['b'=>['c'=>['x'=>null, 'y'=>123]], 'x'=>123],'x'=>['x'=>123], 'x'=>123])); setProperty(321, $config, 'a','b','c','x'); setProperty(321, $config, 'a','b','c','y'); But I wish the function to work regardless of property depth and came up with the following. Recommendations for a cleaner way? Maybe I should be working with arrays and array_merge_recursive()? function setProperty($value, stdClass $config, array $properties) { $property=array_shift($properties); if(!count($properties)){ if(!isset($config->$property) || is_null($config->$property)) { $config->$property=$value; } } else { if(empty($config->$property) || !is_object($config->$property)) { $config->$property=new \stdClass(); } setProperty($value, $config->$property, $properties); } } $config=json_decode(json_encode(['a'=>['b'=>['c'=>['x'=>null, 'y'=>123]], 'x'=>123],'x'=>['x'=>123], 'x'=>123])); setProperty(321, $config, ['a','b','c','x']); setProperty(321, $config, ['a','b','c','y']);
Similar TutorialsHi there, I am just wondering which way is the correct one if you want to create object properties/attribute dynamically at run time using magic method __set(), __get(), for example: class Foo{ public $data = array(); public function __set($name,$value){ $this->data[$name] = $value; } public function __get($name){ if ( isset($this->data[$name]) ){ return $this->data[$name]; } } } Or using the below way class Foo{ public function assign(array $data){ foreach($data as $key => $value){ $this->$key = $value; } } } I just encountered the second way in many places and I am totally confused . Is the __set() method called implicitly by the PHP engine in the second way or what? how come this is considered as a valid code ? your usual help is appreciated There's probably an obvious reason but I can't seem to find it... I start with the $_POST array, received from a form: Code: [Select] array(9) { ["Name"]=> string(3) "KTN" ["SQLServer"]=> string(24) "10.6.11.20\VSQLI028,1433" ["Username"]=> string(2) "GF" ["Password"]=> string(2) "GF" ["MasterDB"]=> string(11) "GFMaster_KN" ["Version"]=> string(3) "4.9" ["Prod"]=> string(1) "1" ["Monitored"]=> string(1) "0" ["button"]=> string(38) "updateColumnName=EnvironmentID;Value=1" } I get the button value from the array, and unset the button array value. Code: [Select] function load_POST($name) { //returns value and removes it from $_POST array. returns NULL if not existing. $debug = 0; if ( $debug == 1 ) { $backtrace = backtrace(); echo __FUNCTION__."()"; echo " <i>called by ".basename($backtrace[1]['file'])."</i><br/>\n"; } $post = NULL; if( array_key_exists($name, $_POST) ) { $post = urldecode($_POST[$name]); if ( $debug == 1 ) { echo "post $name, value: $post<br/>\n"; } } else { if ( $debug == 1 ) { echo "post $name: doesn't exist<br/>\n"; } } unset($_POST[$name]); return $post; } $_POST is now: Code: [Select] array(8) { ["Name"]=> string(3) "KTN" ["SQLServer"]=> string(24) "10.6.11.20\VSQLI028,1433" ["Username"]=> string(2) "GF" ["Password"]=> string(2) "GF" ["MasterDB"]=> string(11) "GFMaster_KN" ["Version"]=> string(3) "4.9" ["Prod"]=> string(1) "1" ["Monitored"]=> string(1) "0" } Then I create the object to assign the values to: Code: [Select] object(Environment)#1 (9) { ["EnvironmentID"]=> NULL ["Name"]=> NULL ["SQLServer"]=> NULL ["Username"]=> NULL ["Password"]=> NULL ["MasterDB"]=> NULL ["Version"]=> NULL ["Prod"]=> int(0) ["Monitored"]=> int(0) } So far so good Then, for each remaining $_POST value, I update the Object accordingly: First one, parametername: Name, parameter: KTN Code: [Select] object(Environment)#1 (10) { ["EnvironmentID"]=> NULL ["Name"]=> string(3) "KTN" ["SQLServer"]=> NULL ["Username"]=> NULL ["Password"]=> NULL ["MasterDB"]=> NULL ["Version"]=> NULL ["Prod"]=> int(0) ["Monitored"]=> int(0) ["ColumnName=EnvironmentID;Value=1"]=> object(stdClass)#3 (1) { ["ColumnName"]=> string(1) "1" } } And there we have the problem, for some reason the button value is added to the object somehow... Any ideas? Thanks in advance! Hi Guys, im really hoping one of you php guru's can shed some light on this as its being bugging me for months... Im trying you access a php include, in a page 1 directory deep into a site (say one down from the index.php) - with no luck. My includes are in a folder that is on the same level as the index.php file for the website. Iv tried using this way: <? include("../includes/footer.php"); ?> And this way: <?php include $_SERVER['DOCUMENT_ROOT'] . "includes/footer.php"; ?> It works locally (using MAMP), but not live on the net. Im getting this error: Warning: main() [function.main]: open_basedir restriction in effect. File(/ext/default/includes/footer.php) is not within the allowed path(s): (.:/tmp) in /ext/f/fo/fourthelement.com/html/sita/resources/members_area.php on line 53 Warning: main(/ext/default/includes/footer.php) [function.main]: failed to open stream: Operation not permitted in /ext/f/fo/fourthelement.com/html/sita/resources/members_area.php on line 53 Warning: main() [function.include]: Failed opening '/ext/default/includes/footer.php' for inclusion (include_path='.:/usr/share/php:/usr/share/pear') in /ext/f/fo/fourthelement.com/html/sita/resources/members_area.php on line 53 Really appreciate anyone who has a few minutes to look at this. Cheers Guys Mike good evening folks, i have a question regarding the foreach syntax when needing to access something say 3 levels deep into the json architecture here's the example I'm trying to accomplish but when echoing it's not returning the value i need from 3 levels deep. I believe i just don't understand the correct syntax so here's the example any help would he sincerely appreciated.
https://pastebin.com/mEBiMUW5 I came across the PHP clone method. Does this clone first level fields and methods or does it also do deep copying e.g. copying references to those fields. For example, a field may be an array. Does it make a copy of the actual array or does it refer to the same array position in memory, so if the original changes, then the copy's changes as well?
Hey all, I want to have an object that has a property which is an object containing instances of other objects. I try this: Code: [Select] class Blog extends Posts { public $has_posts; public function __construct($a,$b,$c){ $has_posts = (object) array_merge((array) $a, (array) $b, (array) $c); } } class Posts { public $b; public function __construct($b){ $this->b = $b; } } $post1 = new Posts(1); $post2 = new Posts(2); $post3 = new Posts(3); $blog = new Blog($post1,$post2,$post3); var_dump($blog->has_posts); //null foreach($blog->has_posts as $post){ //Invalid argument supplied for foreach() echo $post->b; } But as you see, has_posts is null, not an object containing other objects. Thanks for response. __call is used when a method has been called, is there anything similar to __call but for properties? I wanted to use __get, but that is only for private properties... I am working on a header for a website and the code below pulls the file location for the image. I am wondering how (if possible) I could apply the repeat-x tag to the image. I know it can be done with html/css but I'm not sure how to go about it in PHP. Thanks in advance. Code: [Select] <?php include 'db.php'; $result=mysql_query("SELECT location FROM header WHERE page='home'"); $row = mysql_fetch_row($result); echo "<img src=images/".$row[0] . "> "; ?> I'm doing some basic object coding to get my head around OOP PHP, but I've come across something I can't get to work. I've got two identical peices of code, MyClass is defined, MyClass2 is then defined as an extension of MyClass. MyClass has three properties Public, Private and Protected. In my first example I can access Public and Protected via a method in MyClass2, this class does NOT have a constructor. The second example has a constructor but I cannot access Public: Code: [Select] <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <body> <?php ECHO "MyClass2 does not have a constructor, Public & Protected both echo correctly from MyClass2->printHello!!!<BR>"; /** * Define MyClass */ class MyClass { public $public; protected $protected; private $private; protected $varXXX; function __construct() { $this->public = "Public"; $this->protected = "Protected"; $this->private = "Private"; //$this->printHello(); } function printHello() { echo $this->public . "!!!<BR>"; echo $this->protected . "!!!<BR>"; echo $this->private . "!!!<BR>"; } } /** * Define MyClass2 */ class MyClass2 extends MyClass { // We can redeclare the public and protected method, but not private protected $protected = 'Protected2'; /* function __construct() { echo $this->public . "#<BR>"; echo $this->protected . "#<BR><BR>"; //echo $this->private . "???<BR>"; } */ function printHello() { echo $this->public . "???<BR>"; echo $this->protected . "???<BR><BR>"; //echo $this->private . "???<BR>"; } } $obj = new MyClass(); //echo $obj->public . "<BR>"; // Works //echo $obj->protected; // Fatal Error //echo $obj->private; // Fatal Error //$obj->printHello(); // Shows Public, Protected and Private $obj2 = new MyClass2(); //echo $obj2->public; // Works //echo $obj2->private; // Undefined //echo $obj2->protected; // Fatal Error $obj2->printHello(); // Shows Public, Protected2, Undefined ?> </body> </html> RESULTS IN: Public??? Protected??? Code: [Select] <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <body> <?php ECHO "MyClass2 DOES have a constructor, Public does not work from MyClass2->printHello!!!<BR>"; /** * Define MyClass */ class MyClass { public $public; protected $protected; private $private; protected $varXXX; function __construct() { $this->public = "Public"; $this->protected = "Protected"; $this->private = "Private"; //$this->printHello(); } function printHello() { echo $this->public . "!!!<BR>"; echo $this->protected . "!!!<BR>"; echo $this->private . "!!!<BR>"; } } /** * Define MyClass2 */ class MyClass2 extends MyClass { // We can redeclare the public and protected method, but not private protected $protected = 'Protected2'; function __construct() { echo $this->public . "#<BR>"; echo $this->protected . "#<BR><BR>"; //echo $this->private . "???<BR>"; } function printHello() { echo $this->public . "???<BR>"; echo $this->protected . "???<BR><BR>"; //echo $this->private . "???<BR>"; } } $obj = new MyClass(); //echo $obj->public . "<BR>"; // Works //echo $obj->protected; // Fatal Error //echo $obj->private; // Fatal Error //$obj->printHello(); // Shows Public, Protected and Private $obj2 = new MyClass2(); //echo $obj2->public; // Works //echo $obj2->private; // Undefined //echo $obj2->protected; // Fatal Error $obj2->printHello(); // Shows Public, Protected2, Undefined ?> </body> </html> RESULTS IN: # << Missing the property's contents Protected2# ??? << Missing the property's contents Protected2??? Any ideas why I cannot access the property's contents in the second example when the only difference is that it has a constructor? I have a bunch of quasi-static values that must be available to the application. Most of them are set based on settings in a configuration file. Others are based on GET, COOKIE, or SESSION values, and utilize the database to get the actual values. The values will never be written to or modified by the application, only read.
It seems to me that I could create some sort of superclass which includes static methods and properties, and I could access any value by something like superclass::get('some.value'); I could design the class so that the values are queried from the DB or obtained from a parsed file only the first time they are requested, and for future requests, retrieved from a static property.
That being said, I have been told from more than one person that I am just doing it "wrong".
Please let me know what is wrong about it.
Thank you
I have a Soup object in a Bowl object in a Microwave object. The Microwave object has the methods: receiveItem(Bowl $b) cookItem(???) I want the Microwave to be able to set the Soup->temperature but I'm not how to do that? Make sense? TomTees Hello i just want to code a function for my editor that help me to do this: i copy a page with some note and picture in my editor,when i press send bottom editor find IMG tag in and upload it in my own server i can write a function for finding IMG tag and upload,but i don't know how i have to add automatic upload to my server,is there any body here can help me for coding this? or do you know one script or editor that have this properties on it? i use my sample editor I have wizard that asks several predefined questions to find-out user needs. at the end it must offer some items based on user answers. all of available items have some properties in common and one or two specific properties. what is the best way or algorithm to do this in JavaScript? e.g: Item 1 Properties: Name Weight Color Size Item 2 Properties: Name Size Weight Item 3 Properties: Name Color Size Thanks. Hi, I'm not 100% sure if this is HTML, PHP or Javascript, but my best guess is PHP. When you upload an image on Facebook, it automatically gathers the data about the image, i.e. size, device used (i.e. Canon, iPhone), title and description. It then outputs this on the page. Is there anyway to do this with PHP, instead of having to type all the information out again and upload that with the photo to a database? Cheers. I implemented an endpoint which receives name/value pairs: PUT someresource/123 {"name": "description", "value": "Some new description"} I think I made a mistake, and should have implemented it as: PUT someresource/123 {"description": "Some new description"} The reason I think so is updating multiple properties is only (easily) possible using the later: PUT someresource/123 {"description": "Some new description", "otherProperty": "bla bla bla"} Assuming I am not using some 3rd party client library which only works with name/value pairs, any compelling reason why one shouldn't default to the later approach with key/values? Is this an effective way of accessing the $_GET and $_POST properties? I can see that the native $_GET function has been looped through so that $varName would be for example "username" and $value would be "Jeremy". Then they are both stored into an array called $getVars? Is this the best way of doing it, if not then why? foreach($_GET as $varName=>$value) $getVars[$varName]=trim(clean($value, 100)); foreach($_POST as $varName=>$value) $postVars[$varName]=trim(clean($value, 100));[/php] Kind regards, laanes This topic has been moved to Application Frameworks. http://www.phpfreaks.com/forums/index.php?topic=326397.0 Hi Can you call Class A's methods or properties from Class B's methods? Thanks. I made a website in PHP mvc framework. Now I want to remove "public" keyword from URL. I tried by removing require "../app/init.php"; these dots and bringing htaccess & index.php file in root directory. But it doesn't work. I searched on google but didn't find anything. Here is my index page code: Quote
<?php require "../app/init.php"; $app = new App();
and my htaccess code: Quote RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f Please give me a solution to it. Thank you can anyone tell me why $username is not setting properly? the password is, but $username is no. it is setting as blank: Code: [Select] if ($_POST['go']) { //Connect to the database through our include if ($_POST['logid'] == ";5757120050531338739=49121200000?"){ $username="oldcheney"; $username = stripslashes($username); $username = strip_tags($username); $username= strtolower($username); $username = mysql_real_escape_string($username); $password="password";} else if($_POST['logid']==";5757120050531338721=49121200000?"){ $username="yankeehill"; $password="password";} else if($_POST['logid']=="%6277202936423578^00000000^X?"){ $username="holdrege"; $password="password";} $password = md5($password); |