Home >Backend Development >PHP Tutorial >Why is the order of defining attributes in a class not affected?

Why is the order of defining attributes in a class not affected?

WBOY
WBOYOriginal
2016-08-04 09:21:551096browse

Why is defining a variable in a normal function different from defining a property in a class? In the a() function, variables must be defined in front. If $a =1 in the a() function is placed after return, an error will be reported. Why is there no error in the class? Although big hands may think it’s childish, I don’t understand this question

<code>function a(){
    return $a;
    $a=1;
}
echo(a());
----------------------------------------------
class aa{
    function bb(){
          return $this->name;
        }
    public $name=4;    
}
$a=new aa();
$b=$a->bb();  
echo $b;</code>

Reply content:

Why is defining a variable in a normal function different from defining a property in a class? In the a() function, variables must be defined in front. If $a =1 in the a() function is placed after return, an error will be reported. Why is there no error in the class? Although big hands may think it’s childish, I don’t understand this question

<code>function a(){
    return $a;
    $a=1;
}
echo(a());
----------------------------------------------
class aa{
    function bb(){
          return $this->name;
        }
    public $name=4;    
}
$a=new aa();
$b=$a->bb();  
echo $b;</code>

Because classes are compiled first and then executed, while process-oriented execution is streaming.
This is generally the case. This is what I learned from JS.

The most basic explanation is $a=new aa();At this time, the attribute $name has been assigned a value, but function bb() has not been executed yet.
In fact, object management is very complicated. To put it simply, no matter how you write it, it has been preprocessed at runtime. All properties are allocated memory when instantiated and then constructed.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn