Solved

Setting defaults for a class

Posted on 2013-01-17
11
180 Views
Last Modified: 2013-02-02
I'm trying to set a range of defaults for a class, so a user can (if they want) set a variable, if it isn't set then the constructor would set the default.

So Ive done it as:-
class protoMenu{
    function protoMenu($arrMenu) {
        if (isset($arrMenu['divContentsIDb'])) {
            $arrMenu['divContentsIDb'] = "divMenuContents";
        }
	var_dump($arrMenu); 
    }
}

$Menu = new protoMenu(array("divContentsID" => "divMenuContents", "divMenuID" => "divMenu"));

Open in new window


However after the var_dump runs $arrMenu['divContentsIDb'] does not exist.

I wanted to use an array to set everything, as then its easier to enter data during setup, for soo many possibilities to setup the class.

What am I doing wrong? :-(
0
Comment
Question by:tonelm54
  • 4
  • 3
  • 3
  • +1
11 Comments
 
LVL 34

Expert Comment

by:gr8gonzo
ID: 38789458
You need to use $this-> to reference class properties, like:

class X
{
   public $property = "foo";

   public function X()
   {
     $this->property = "bar";
     echo $this->property;
   }
}

(For others' reference)
Check out my articles on OOP PHP:

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2626-Beginning-Object-Oriented-Programming-in-PHP.html

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2631-Advanced-Object-Oriented-Programming-in-PHP.html
0
 

Author Comment

by:tonelm54
ID: 38789466
When I try $this-> it doesn't reference the variable passed into the function.

I'm wondering if this variable is read-only?
0
 

Author Comment

by:tonelm54
ID: 38789559
So what I'm basically trying to do is:-
    function protoMenu($arrMenu) {
            $arrMenu['divContentsIDb'] = "divMenuContents"; 
    }

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 38789671
This will probably be easier if you adopt PHP5 Object Notation.
http://php.net/manual/en/language.oop5.php

See http://www.laprbass.com/RAY_temp_tonelm54.php

<?php // RAY_temp_tonelm54.php
error_reporting(E_ALL);
echo "<pre>" . PHP_EOL;

class ProtoMenu
{
    public function __construct($arrMenu=array('divContentsIDb' => "divMenuContents"))
    {
        $this->arrMenu['divContentsIDb'] = $arrMenu;
    }
}

// DEFAULT VALUES
$test = new ProtoMenu;
var_dump($test);

// OVERRIDE THE DEFAULT VALUES
$Menu = new protoMenu(array("divContentsID" => "divMenuContents", "divMenuID" => "divMenu"));
var_dump($Menu);

Open in new window

0
 
LVL 20

Expert Comment

by:Mark Brady
ID: 38790338
Your var_dump() should work but the reason it is not is because you have a typo when you are instantiating the class object on line 10 of your code.

array("divContentsID" => "divMenuContents"

should be

array("divContentsIDb" => "divMenuContents"

Fix that issue then try it again.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 20

Expert Comment

by:Mark Brady
ID: 38790358
Oh and I forgot to add that you need to have a constructor like Ray suggested if you want to pass values into it when instantiating (creating the class object).  The only other way to do it is to instantiate it like this...

$proto = new protoMenu();
// now to just run your function you would need to do this next..

$proto->protoMenu(array("divContentsID" => "divMenuContents", "divMenuID" => "divMenu"));

That will give you your var_dump but that is ugly and pointless. Your function should either set some class property value of return something.

$array = array(
    "divContentsID" => "divMenuContents",
    "divMenuID" => "divMenu"
    );

$result = $proto->protoMenu($array);

Inside your function get it to return something or set some value you can use later on.
Hope this helps
0
 
LVL 20

Accepted Solution

by:
Mark Brady earned 500 total points
ID: 38790361
Geez I copied and pasted your typo into my last reply. Sorry about that. "divContentsID" should all be "divContentsIDb"
0
 

Author Comment

by:tonelm54
ID: 38792001
Sorry, I dont think Ive explained my issue correctly.

divContentsIDb does not exist in the array passed through to the constructor, so if it doesnt exist I wanted to add it to the parameter variable for the constructor.

So in basic terms, what Im trying to do is get the following code working:-
    function protoMenu($arrMenu) {
            $arrMenu['divContentsIDb'] = "divMenuContents"; 
    } 

Open in new window


From what I understand $arrMenu is a variable, its not a reference, and not read-only so I should be able to manipulate it.

From reading the comments, I should create the array outside the call and then pass the values again, in my head this is a waste of code and memory (even if not by much), as you need to create the variable for the array, then copy that variable (ok you could copy by reference) into the class, then Im going to be copying the passed array in the class into its own variables.

I know I could add code above in the class to add a default, and if it exists in the array change the default, and I know I could create a method to set the variable, but I thought this way is much tidier and simplier, and although I might still put a method in to set the variable, I thought by passing everything I wanted in the constructor of my class would be a good idea, and reduce the end user from having to type several lines of code to set up the class, instead everything can be done in one line :-)
0
 
LVL 20

Expert Comment

by:Mark Brady
ID: 38792741
Wow that's a mouth full of confusing information there buddy but let me try a decipher it as best I can.

1: You want to set this value ($arrMenu['divContentsIDb'] = "divMenuContents"; ) when you construct the class.

2: Obviously you want this array to be available outside of a function right? So other functions and code can use the value...
<?php
class ProtoMenu {

    public function __construct($array)  {
        if (!isset($array['divContentsIDb'])) $this->arrMenu['divContentsIDb'] = "divMenuContents";
    }
}

// so first it checks to see if the value is already set. If not, it sets it.
Now you can use it anywhere in the scope of your class.

$some_array = array('someKey' => 'someValue');
$proto = new protoMenu($some_array); // construct the class

print_r($proto->arrMenu);

?>

I think I see where you are going but your explanation borders on confusion sorry to say :)
0
 
LVL 34

Expert Comment

by:gr8gonzo
ID: 38793068
So basically you want all your defaults into a single array property of the class?

class X
{
   // The default properties
   public $properties = array(
      "varA" => 123, 
      "varB" => "XYZ",
   );

   public function X($properties)
   {
     // Merge, making sure any user-defined properties take priority
     $this->properties = array_merge($this->properties,$properties);
   }
}

Open in new window


The user would then use the class like:

<?php
$X = new X(array("varA" => 456));
print_r($X->properties); // Would show that varA = 456, and varB = XYZ
?>

Open in new window

0
 
LVL 34

Expert Comment

by:gr8gonzo
ID: 38793080
For what it's worth, if that's what you're trying to do (what I said above), don't do it that way. It might save a few lines of setup code, which is nice, but it also strips out the ability to take advantage of some of the benefits of OOP and also becomes a little less efficient in terms of memory (since arrays are becoming less memory-efficient with newer versions of PHP in favor of objects).
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now