Define variables outside the PHP class - php

I m using zend.
I want to define the below code outside the controller class & access in different Actions.
$user = new Zend_Session_Namespace('user');
$logInArray = array();
$logInArray['userId'] = $user->userid;
$logInArray['orgId'] = $user->authOrgId;
class VerifierController extends SystemadminController
{
public function indexAction()
{
// action body
print_r($logInArray);
}
}
But it does not print this array in index function on the other hand it show this array outside the class.
How it is possible.
Thanks.

To access a global variable from inside a method/function, you have to declare it as global, inside the method/function :
class VerifierController extends SystemadminController
{
public function indexAction()
{
global $logInArray;
// action body
print_r($logInArray);
}
}
In the manual, see the section about Variable scope.
Still, note that using global variables is not quite a good practice : in this case, your class is not independant anymore : it relies on the presence, and correct definition, of an external variable -- which is bad.
Maybe a solution would be to :
pass that variable as a parameter to the method ?
or pass it to the constructor of your class, and store it in a property ?
or add a method that will receive that variable, and store it in a property, if you cannot change the constructor ?

print_r($GLOBALS['logInArray']);
http://php.net/manual/en/reserved.variables.globals.php

You can store the user in many ways and access it in more clean manner. You can store it in Zend_Registry and then use Zend_Registry::get('user') where you need to retrieve the user. You can also store it as a parameter of request object, and then in a controller simply do $user = $this->_getParam('user');
If you need access to the user array in many controllers that inherit from the SystemadminController, what you can do is store it as a protected property of the SystemadminController (eg. protected $_user). Then all you need to do in child controllers is access $this->_user.

Related

When and How to make class variables with PHP?

Newbie question, i have variables inside my class method, do i have to make them class variables where i can access them using $this? If no, please explain when do i use or make a class variables?
private function is_valid_cookie()
{
$securedtoken = $this->input->cookie('securedtoken');
// Checks if the cookie is set
if (!empty($securedtoken)) {
// Checks if the cookie is in the database
$s = $this->db->escape($securedtoken);
$query = $this->db->query("SELECT cookie_variable FROM jb_login_cookies WHERE cookie_variable=$s");
if ($query->num_rows() != 0) {
// Now let us decrypt the cookie variables
$decoded = unserialize($this->encrypt->decode($securedtoken));
$this->login($decoded['username'], $decoded['password']);
return true;
} else {
return false;
}
} else {
return false;
}
}
as you guys can see, i have variables $securedtoken and $decoded = array(), i cant decide if i have to make them class variables and just access them with $this
I actually try to minimize use of class-level variables to cases where they are going to be common amongst multiple methods, or they are going to be referenced from code outside the class (either directly or via getters/setters). If the variable is just needed in local scope for a method, do not pollute the class with it.
You'll want to make class variables when you are trying to share those variables throughout different functions in the class. You'll then need different Access Modifiers (public, private, protected) for these properties depending on whether or not outside code can view them, child classes can view them, or nothing at all.
You do not have to make them instance variables. You can make them static variables too, or constant variables! You use a class variable to describe attributes of a class. ie what a class has.
Its important to get your terminology correct too. You are asking about making the variable and instance variable. A class variable (http://en.wikipedia.org/wiki/Class_variable) refers to a static variable
For your specific example if your two variables are only used in that function you should not make them instance variables. There is no reason to share them accross the class
On the other hand if you need to use them again in other methods or in other places than yes. you should.
Deciding what kind of variable you want and what kind of access is a design decision.
Good places to start are object oriented php overview. http://php.net/manual/en/language.oop5.php
And basic beginner tutorials
http://www.killerphp.com/tutorials/object-oriented-php/
You do, yes. You can declare class variables like this:
class Dog
{
protected $name = 'Spot';
public function getName()
{
return $this->name;
}
}
You can read more about properties (member variables) in the documentation.

$this->var or $var

I just started using OOP / CodeIgniter. I want to get assign the form input to variables. I wonder which one I should use $this -> var or $var and how they differ from each other? Thanks.
For example
$agree = $this -> input -> post( 'agree' );
OR
$this -> agree = $this -> input -> post( 'agree' );
Both will work fine like:
if ($agree) { }
OR
if ($this -> agree){ }
Thanks
It's a matter of scope
<?php
class Example extends CI_Controller
{
private $agree1;
public function __construct()
{
parent::__construct();
}
public function index()
{
$agree2 = $this->input->post( 'agree' );
$this->agree1 = $this->input->post( 'agree' );
// within this context both are accessable
// these will print the same
var_dump($agree2);
var_dump($this->agree1);
// call the helper function
$this->helper();
}
private function helper()
{
// within this context $agree2 is not defined
// these will NOT print the same. Only the 2nd will print the content of the post
var_dump($agree2);
var_dump($this->agree1);
}
}
?>
This is really a matter of preference when it comes to extra local variables. As general guidance, I would use $var if the variable is only pertinent to the method, and $this->var if it makes sense for other methods to use this variable too.
If you are just collecting the input and handling it in that method, I would just use a local variable. Class members are normally used for things relevant to the class/object, for example a class representing a vehicle might have a $number_of_wheels variable.
I'm assuming that you're talking about what to use inside a controller/action pair?
$this->var actually refers to a property of your controller class named var.
$var means that it's a locally (function) scoped variable
If you do not specifically want to access a class property, don't use $this. Just use $var and have it accessible only within the scope of the function.
If you are actually referring to a class property and you want this property to be acessible by all methods in your class, make sure you declare it in your class definition on top.
It depends on whether you want to set a local variable or an object variable.
You should have your object variable declared at the beginning of the class (e.g. private $var) - they are accessible from different methods across the class.
Local variable is accessible only in the scope of current method.
If you use $this->var then you are referring to a class variable. If you are assigning it to just $var then you are referring to a local variable. I am gussing you need to make use of the following if you don't need the form values to be available to other methods:
$agree = $this->input->post('agree');
$this->agree) if you're going to use it in other functions of the class, $agree if using it within the current scope, meaning inside the function making it a local variable only.
I think only $this->agree works, however, I have not tested this.
Ad#m

Should I place variables in class or constructor? PHP

My question(s) is one of best practices for OOP. Im using Codeigniter framework/PHP.
I have a class:
class Test() {
var $my_data = array();
function my_function() {
//do something
}
}
Is it ok to declare $my_data in the class like that? or should it go in the constructor? Basically every function will be writing to $my_data so in a sense it will be a class-wide variable(global?, not sure about the terminology)
Also, should I use var or private ? is var deprecated in favor of declaring the variables scope?
If you want $my_data to be available to all methods in Test, you must declare it at the class level.
class Test {
private $my_data1 = array(); // available throughout class
public function __construct() {
$my_data2 = array(); // available only in constructor
}
}
var is deprecated and is synonymous with public. If $my_data doesn't need to be available outside of Test, it should be declared private.
If it belongs "to the class", put it in the class. If it belongs "to an instance of the class", put it in the constructor. It kinda sounds like you should be using the session, though.
its fine if you declare the variable outside constructor.
actually codeigniter will not let you give any parameter at your constructor.
and the variable will automatically assigned value when the class is instantiated.
for default, any of php variable and function with in a class will be have a public access.
i don't really thing you need to use access modifier at codeigniter.
the library it self don't define any access modifier.

Setting variable to be accessed by different methods within the class

I have a controller with different methods, but they all have to set a variable containing a list of items to be shown in a box in the view, I extract data from the DB and set $data['categories'].
Can I set it once and have it visible by all methods?
In addition to this, if you are only using $this->data to get the values into your views, instead of doing:
$this->data->something = 'whatever';
Then doing
$this->load->view('something', $this->data);
You can instead set it with:
$this->load->vars('something', 'whatever');
Then later on use the normal localized $data array (or whatever you like) as the variable will be globally available to all loaded view files.
I'm not suggesting either way is better, just letting you know how else it could be done. I personally use a mix of these methods. :-)
make it a property of the class
class Controller {
protected $data;
and use '$this' to access in in your methods:
class Controller {
function foo() {
$this->data etc...

Can you get a calling class's variables?

I have a class Page that creates an instance of DB, which is named $db.
In the __construct() of Page, I create the new $db object and I pull a bunch of config data from a file.
Now the DB class has a method _connectToDB() which (attempts) to connect to the database.
Is there a way in the DB class to call the parent class's config array? I don't want to make global variables if I don't have to and I don't want to grab the config data twice.
Pseudo code might look something like this...
$dbUsername = get_calling_class_vars(configArray['dbUserName']);
I find that it's often easier to initialise all the "important" objects close to whatever variables they need to know. You could try it this way:
/* Code to get config variables here */
$DB = new DB($config);
/* You might want to delete the database password from $config here */
$Page = new Page($config, $DB);
Doing it this way means you can also do type-checking on the database object if you want to:
class Page {
function __construct(array $config, DBClass $db) { }
}
You can use static if you want to share variables without passing these:
class page{
static $configArray = [];
function doWhatever(){
$db = new DB();
$db->connectToDB();
}
}
class DB{
function connectToDB(){
$dbUsername = page::$configArray['dbUserName'];
}
}
In this case makes sense to have those data as static, because even if you have a multiple instances of the page class, the config parameters should always be the same.
Anyway I think that could be better to construct and keep the $configArray only in the DB class. If you want to call it from outside you can use the same static logic.
Why not pass the config parameters to the connectToDb function or pass the config data to the constructor of the DB class.
And to directory answer the question: you don't know anything about the outside calling context in your current context.
See debug_backtrace() to get information about calling classes or objects.
Then see Reflection to get more information on the properties of a given class or object.
edit: But for what it's worth, I'd also recommend passing the specific parameters you need. Referencing the caller's data probably constitutes Content Coupling.
You can pass the child a reference to the parent. For example:
class Parent {
function __construct() {
$this->myChild = new Child($this);
}
public function doSomething() {}
}
class Child {
function __construct(Parent $parent) {
$parent->doSomething()
}
}
You may find this odd, since you're still in the parent's constructor, and thus your parent object isn't fully constructed yet. But you can still use $this as a reference to yourself, even in the constructor. You just need to be careful that your child doesn't refer to things in the parent that haven't been initialized yet.
In general there is no easy way to do this. but as a general design issue i can see why your avoid global variables, but in the case of application wide configuration it is perfectly reasonable to have global access to the properties.
you can either make your config data global or just pass the needed properties to the db object initialization.

Categories