ian0mackenzie Posted October 21, 2015 Share Posted October 21, 2015 Hello! Hope it's OK to post this here... I've looked in a few places and, while I've found a few variations of my question, I still have trouble filling in the gaps here.I'm trying to use more classes and more OOP style writing. However I've run into an interesting variable scope scenario and I don't quite understand. I have a class and I want to make a variable of hardcoded values available to each function within the class. The variable is $allowedTags = array( 'strong' => array(), 'a' => array('href' => array(),'title' => array(),'alt' => array(),'class' => array(),'id' => array()), 'em' => array(), ); This is a wordpress thing. It's used to see what HTML tags are allowed in certain form inputs. My question is in two parts.1. What's the best way to accomplish this? The technique I'm using now is as follows: if (!class_exists("ClassName")) { class ClassName { private $allowedTags; function __construct() { $this->allowed_tags = array( 'strong' => array(), 'a' => array('href' => array(),'title' => array(),'alt' => array(),'class' => array(),'id' => array()), 'em' => array(), ); } // End __construct() function functionN(){ //This works! var_dump($this->allowed_tags); } But something is bothering me about this and it leads me to my other question: 2. Why do I have to define these values in __construct instead of at the private $allowedTags; line? I'm clearly missing something about variable scope here. Thanks so much in advance for any input you can provide! Quote Link to comment https://forums.phpfreaks.com/topic/298748-general-question-about-variable-scope/ Share on other sites More sharing options...
Solution Jacques1 Posted October 21, 2015 Solution Share Posted October 21, 2015 You've mixed up two naming styles: $this->allowedTags isn't the same as $this->allowed_tags. If you fix this, you can in fact define the attribute in the class body. Is this the best approach? Well, it's difficult to tell given this very abstract code, but hard-coding the tags inside the class means you won't be able to ever change them (unless you change the class definition, of course). It might make more sense the define the tags outside of the class and pass them through the constructor. Quote Link to comment https://forums.phpfreaks.com/topic/298748-general-question-about-variable-scope/#findComment-1523913 Share on other sites More sharing options...
ian0mackenzie Posted October 21, 2015 Author Share Posted October 21, 2015 Ha! Good observation. Can't believe I missed that. Thanks a bunch for a really straight-forward and meaningful answer. Quote Link to comment https://forums.phpfreaks.com/topic/298748-general-question-about-variable-scope/#findComment-1523914 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.