When and How to make class variables with PHP? - 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.

Related

Does PHP allow you to declare a Class variable without setting it up as a member in the Class definition? [duplicate]

I'm new to the OOP paradigm, so there's probably a simple explanation for this question...
Do you always need to declare public object-wide variables in a class? For example:
<?php
class TestClass
{
var $declaredVar;
function __construct()
{
$this->declaredVar = "I am a declared variable.";
$this->undeclaredVar = "I wasn't declared, but I still work.";
}
function display()
{
echo $this->declaredVar . "<br />";
echo $this->undeclaredVar;
echo "<br /><br />";
}
}
$test = new TestClass;
$test->display();
$test->declaredVar = "The declared variable was changed.";
$test->undeclaredVar = "The undeclared variable was changed.";
$test->display();
?>
In this code, even though $declaredVar is the only declared variable, $undeclaredVar is just as accessible and useable--it seems to act as if I had declared it as public.
If undeclared class variables are always accessible like that, what's the point of declaring them all up front?
That variable isn't uninitialized, it's just undeclared.
Declaring variables in a class definition is a point of style for readability.
Plus you can set accessibility (private or public).
Anyway, declaring variables explicitly has nothing to do with OOP, it's programming-language-specific. In Java you can't do that because variables must be declared explicitly.
If you declare a member inside the class you can set its accessibility e.g
private $varname;
You should always declare your member variables and specify their accessibility within your classes. I like to put this information at the end of the class after my functions.
You should define them as soon as you have enough information to do so. Possibly in the constructor or via setter functions.
It is important to do this because it makes life much easier for people working with your code. They don't have to guess where different properties are coming from or why they're there. Also, most (if not all) IDEs will not pick up on class variables unless you've declared them somewhere. Code completion/hints are one of the many benefits of IDEs and without declaring your variables, you will render that functionality useless.
General OOP paradigm of encapsulation says you should not expose your inner state variables out side that means they should be private, that allows you to change an implementation of your class without need to change the code where you make use of it. It's better practice to initialize variables via constructors and getters and setters method of the class.
In general variables should be initialized as soon as you have enough info to do it properly.
If a class variable needs certain info to be sensibly initialized then that info should be passed to the constructor.
Using PHP's syntax to implicitly declare variables at the point of definition is, IMHO a surefire way to introduce bugs - if your class needs a variable then declare it, and use all of the information hiding that OOP affords you.
As Federico Culloca said "That variable isn't uninitialized, it's just undeclared". Also you didn't define any access modifiers for them so that they behaving like public modifier applied to them.
You may already have known, PHP is a loosely typed language. But a programmer should always follow the best practices and define access modifiers manually. It increases code readability.
You can use private modifier for class level variables and provide accessor and mutator methods (Getters and Setters) for them when needed.
TLDR: Only Define What Isn't in The Default/Public
To define or not define global variables within class scope — ultimately, it is a design decision that should be taken to improve code readability, and nothing more. Personally, I don't "define all of these," and I use the default scope of public (Source: PHP.net -> Visibility). I do that until I actually need to change any of them for a particular need.
The Basic Objection
"But shouldn't that be set so we can define public and private as needed?" : If you need to set a global variable's status, then set it. Until you set it, it is public. So, set it when you need it. Don't write code that does nothing with the hope that one day in the future you'll thank yourself -- odds are you may need to completely revamp everything your old self did. And what if you have hundreds of variables all set to the same default instance? How does that help anyone?
Why Avoid Hardcoding the Accessibility Value on Attributes?
At some point, we will be able to configure the default, and then all that code that hard-coded this class accessibility, or that class accessibility, will need to be reprogrammed. In general, hard-coding is bad, and the large amounts of typing/copying-pasting associated with class attribute access definitions is just not worth the result. Use the default.
It's Really All About Style
If all your class variables public and the extra global definitions (100's of them maybe) doesn't help you, then dump them. If they give structure to your code, though, then keep them. It's something done to help the coder, not the compiler.
Which would you rather have to fix?
This?
class basicscript extends baseformat {
public function __construct($args) {
$this->startUp($args);
return $this;
}
}
Or this?
class basicscript extends baseformat {
public $desired_script;
public $desired_action;
public $object_code;
public $object_parent;
public $object_list;
public $script_location;
public $script_name;
public $script_file;
public $script_extension;
public $script_format;
public $script_format_lower;
public $script_args;
public $authentication_object;
public $cleanser_object;
public $query_object;
public $db_access_object;
public $domain_object;
public $language_object;
public $dictionary;
public $time;
public $cookie;
public $formats_object;
public $version_object;
public $redirect_object;
public function __construct($args) {
$this->startUp($args);
return $this;
}
}

Should I keep variables used only in one class method local or declare them as class properties?

I've been wondering if a class property is instantiated and used only in one class method should it be a class property at all or should it just be a local variable accessible to that class method only?
For example, should I keep a variable only used in one method as a local variable like this:
class myClass
{
public function myMethod()
{
$_myVariableUsedOnlyOnce = "Hello World";
echo $_myVariableUsedOnlyOnce;
}
}
Or should I make the variable a private class property like this:
class myClass
{
private $_myVariableUsedOnlyOnce;
public function myMethod()
{
$this->_myVariableUsedOnlyOnce = "Hello World";
echo $this->_myVariableUsedOnlyOnce;
}
}
Which approach "smells"? What are the benefits to making all method variables class properties other than when I need to print_r() the entire object for debugging purposes?
Thanks
If you need it to have persistence across function calls, a class property would be best so that it moves around as the object does. You also might want to use it for other reasons in future in other functions. However, it does add overhead.
Generally, the class should have some real-world analogue, so if your variable corresponds to something that makes sense e.g. a person class has a $height, then it belongs as a class property. Otherwise, if it's just a part of the internal calculations of a method, then it doesn't really belong attached to the class e.g. a person does not have a $shoelaceIterator or whatever.
I'd argue that a confusing object design would be more of a smell than a potentially small memory overhead (although this depends on how big the variable is).
These local variables are not properties of your object.
They are not defining your object, then they should not be declared as private member.
First I would ask if you really need the variable/property at all if you are only using it once. As for which one "smells", a property is stored in memory for the entire life of the object whereas the variable is only in memory until the method finishes executing.
If you don't need a variable outside the method, it should not be any property of the class. Moreover, accessing local variables is faster.
In a pure design approach I would suggest you to make your choice according to what the attribute/property is supposed to model.
In pure performance terms, having one static attribute is better because memory space won't be allocate with each instance of the class.

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.

Advantage of passing by reference opposed to using global?

im looking at the MVC pattern, and I can see in one example on phppatterns they're passing the model by reference - any benefit of doing this over a global var? Am I missing something obvious?
class MyView extends View {
var $model;
function __construct(&$model){
$this->model =& $model;
}
function productTable($rownum=1) {
$rowsperpage='20';
$this->model->listProducts($rownum,$rowsperpage);
while ( $product=$this->model->getProduct() ) {
// Bind data to HTML
}
}
}
Any reason why you would do this as apposed to using a global variable? i.e.
class MyView extends View {
global $model;
function __construct(){ }
function productTable($rownum=1) {
$rowsperpage='20';
$model->listProducts($rownum,$rowsperpage);
while ( $product=$this->model->getProduct() ) {
// Bind data to HTML
}
}
The problem with global variables is that:
They assume that there is only one implementation of model and view.
They assume that there is only one instance of the model and view (you could have several of each in your application).
They hide the interdependency between components; your view is very strongly affected by the model, but not having to explicitly pass a model into your view makes this implicit.
For other reasons why globals and singletons are "evil" (i.e. just really a poor design decision that you should never make), read avoid global variables, environment variables, and singletons.
Yes -- the advantage is that you could change the implementation of the model without having to modify the View.
I'd suggest to use another tutorial, the one you're using is a bit outdated, and isn't PHP 5. That said, you really shouldn't use global variables, that's never the solution!
But I don't really get why you should even wanna pass it by reference, in PHP 5 it's already passed by reference:
class foo {
public $a;
public function __construct($a) {
$this->a = $a;
}
}
$a = new foo(10);
$b = $a;
$a->a = 20;
echo $a->a.' => '.$b->a; // 20 => 20
If you have multiple (similar) model instances, on which you possibly would like to apply the same view, you would need to explicitly pass the model instance. A global variable assumes there could be only one model instance, and thus creates an artificial limitation.
In general not using global variables is better to help you control the scope of your variables.
I won't mention about why that is a bad thing, because it has been already discussed. One thing that I think you should know is that the code provided there is PHP 4 compatible. In PHP 5 by default objects are sent by reference.

Is PHP class variable definition necessary?

Im new to PHP Object Oriented Programming but I know to code in procedural way.
If this is my PHP Class
<?php
class person {
var $name;
function __construct($persons_name) {
$this->name = $persons_name;
}
function get_name() {
return $this->name;
}
}
?>
and if I access it in my PHP page
$jane = new person("Jane Doe");
echo "Her name is : ".$jane->get_name();
Question:
Is it really necessary to put the var $name; in my PHP class since
I can correctly get an output of Her name is : Jane Doe even without the var $name; in my PHP class?
Not technically, no, PHP is very forgiving to things like this. But it is good practice, if only for documentation purposes.
Probably more importantly, declaring the property explicitly lets you set its visibility. In your example $name is a public property (public is the default visibility in PHP). If you don't need it to be public (it's often safer not to, due to getters/setters allowing better control over what values can be assigned) then you should declare if protected or private.
Semantically, you should, as $name is indeed an attribute of your class. Your constructor already assigns $persons_name to the attribute, but if you left the var $name; out, the rest of your script wouldn't really know that there's such an attribute in your class. Additionally if your constructor didn't assign it right away, person::get_name() would attempt to retrieve an undeclared $name attribute and trigger a notice.
As Brenton Alker says, declaring your class attributes explicitly allows you to set their visibility. For instance, since you have get_name() as a getter for $name, you can set $name as private so a person's name can't be changed from outside the class after you create a person object.
Also, attempting to assign to undeclared class attributes causes them to be declared as public before being assigned.
it is very useful.
imagine you write a bunch of person objects with different names in an array and you will call the names of all objects at another place in your website. this is just possible when you store the name of every particular person.
If i understand correctly, you don't need to declare var $name. You can use PHP's magic methods instead, in this case __set and __get.
Edit: there's a small introduction about magic methods # Nettuts.

Categories