Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class - variable declaration

Tags:

When the declaration of a PHP class variable we cannot perform any expressions, e.g.:

class A
{
    $a = 10 + 5;
}

only we can just provide constants e.g.:

class A
{
   $a = 100;
}

Can anybody knows why its like that?

like image 686
akhil.cs Avatar asked Feb 21 '14 18:02

akhil.cs


People also ask

How do you declare a class variable?

Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.

What is a class variable example?

Class Variables In the case of the Bicycle class, the instance variables are cadence , gear , and speed . Each Bicycle object has its own values for these variables, stored in different memory locations. Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier.

How do you declare a class variable in C++?

Defining Class and Declaring Objects A class is defined in C++ using keyword class followed by the name of class. The body of class is defined inside the curly brackets and terminated by a semicolon at the end.

How do you declare a class variable in Python?

A class variable is declared inside of class, but outside of any instance method or __init__() method. By convention, typically it is placed right below the class header and before the constructor method and other methods.


1 Answers

That is because expression is not allowed as field default value. Make use of constructors to initialize the variables instead.

I suggest you do like this..

class A
{
    public $a;

    function __construct()
    {
        return $this->a = 10 + 5;
    }
}

$a1 = new A;
echo $a1->a; //"prints" 15
like image 83
Shankar Narayana Damodaran Avatar answered Oct 06 '22 20:10

Shankar Narayana Damodaran