When Should I Declare Variables in a PHP Class

When should I declare variables in a PHP class?

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.

Class - variable declaration

You cannot use statement or function, just a scalar value. This is because class variables are initiated in compile time (before runtime). Class constructor should be used to initiate property with statement/function.

Do I need to declare a variable before initialise it in PHP constructor

My question is why the test() method can access the test variable?

PHP unlike some other languages allows you to assign values to variables without first declaring them. The interpreter will initialize them for you. This is poor practice because it makes code harder to read and debug, and because it can cause errors if you try to read a variable that was never declared:

<?php
$nonexistentArray['key'] = 7; //Bad practice, but PHP won't complain
$a = $fakeArray['key']; //Undefined variable error

Even in the second case, PHP will continue to execute the rest of the script, but it will complain.

Is the test a global variable?

No. It lives in the local scope.

<?php
function myFunc(){
//$arr was never declared, but PHP won't complain
$arr['key'][]=7;
}
myFunc();

//Undefined var error. The $arr that was initialized in myFunc is not global
print_r($arr);

A good IDE will complain if you try to use a variable that you never declared. In your case, when in the constructor you do:

$this->test = 'helloworkd';

PHP will initialize this class property for you. Now the rest of your code can use it, including the test() method. If it seems like a global var, it's not. It's a class property. If you tried to access it as just test from outside the class, you would not be able to. You'd have to use the accessor operator -> in $test->test or $this->test.

Class works without declaring variables?

Every object in PHP can get members w/o declaring them:

$mycar = new car;
$mycar->model = "Mercedes";
echo $mycar->check_model(); # Good car

That's PHP's default behaviour. Those are public. See manual.

When To Declare Properties Of A Class?

The way I think of these things is that an object is a code representation of a real life object (duh). The car example above is a good one. For most real life objects there are attributes and actions. If our object is person, it will have attributes like name, height, weight, hair color. Then, our person will have actions, like run, sleep, eat.

The actions will be methods and the attributes will be properties. Properties will either be used in the actions or by other parts of the program which need to check the state of your object, IE, another part of your program asks the person how tall it is right now.

In most cases, return values and arguments will not be properties. A notable exception would be arguments you use to instantiate an object, as those will typically be needed by your other methods. As far as variables used within a method, these should be properties if they define the overall state of the object, but if you are creating a variable, like a counter, inside your method, that is just needed to accomplish the goal of the method, it doesn't make sense for it to be a property of your object.

I would start out by erring on the side of fewer properties. If you get to a point where you need a property to accomplish something, then create it. I wouldn't create them until I have a direct need. This way, you'll begin to get a feel for what properties an object will need in order to function logically.

I hope that makes a little sense.

What is the purpose of declaring variables in a class

Both variants are correct but the second one is lacking when getting testvar before you initialize it.

If you call $test->getTestvar(); before you set it with $test->setTestval('bla bla');, you will get a warning, something like:

Notice: Undefined property: Testclass::$testvar

The second variant also lacks the property visibility part (i.e. private, protected). More about visibility.

The declaration of class properties above methods is a good practice, it's taken from strict oop-languages like java.

PHP classes - is it preferable to use normal variables instead of properties?

It's somewhat vague what you're asking, but if valueToUseHere is not used outside of doStuff, then don't make it a property!

class someClass {

public function doStuff() {
$valueToUseHere = 60;
// Do more stuff here...
}

}

If there's no reason to share that value with other methods of the class or with the outside world, then there's no reason to clutter up your object with all sorts of properties. Not only may this cause tricky bugs with preserved state, it also forces you to be unnecessarily careful with your variable names across all object methods.

Dynamically declaring Variable inside a class in php

Just use the {} syntax:

function __construct($array)
{
foreach ($array as $key => $value)
{
$this->{$key} = $value;
}
}


Related Topics



Leave a reply



Submit