0

I have been working with PHP for a while and just started with Python. there is a feature in Python that i came across while learning.

IN Python

class A:
  #some class Properties

class B:
    a = A()  # assiging an expression to the class Property is possible with python.

IN PHP

class A{

}

class B{
  $a = new A();   // PHP does not allow me to do this.

  // I need to do this instead.
  function  __construct(){
    $this->a = new A();
  }
}

I would like to know why. How python complies code differently and if there is any way i can do this with PHP.

Mohan
  • 4,677
  • 7
  • 42
  • 65
  • The answer to "why" is "because they are completely different languages." If you've been working with PHP for a while, you probably already know the proper PHP way to do it. Writing one language in another never has good results. – TigerhawkT3 Jun 07 '16 at 10:49
  • In case of python interpreting the language, it would go level scope based, tries to analyze what has to be initialized when it finds the function scope. – Nagaraj Tantri Jun 07 '16 at 10:51
  • That's somewhat akin to [static](http://php.net/manual/en/language.oop5.static.php) class variables in PHP. See http://stackoverflow.com/questions/68645/static-class-variables-in-python. – Ilja Everilä Jun 07 '16 at 10:59

2 Answers2

2

in Python

Variables declared inside the class definition

class A:
  #some class Properties

class B:
    a = A()  # assigning to the class Property
    # class properties are shared across all instances of class B 
    # this is a static property

Variables declared inside the class constructor

class A:
  #some class Properties

class B:
    def __init__(self):
        self.a = A()  # assigning to the object Property
        # this property is private to this object
        # this is a instance property

More reading for python static and object attributes

in PHP

inPHP, singleton pattern uses the concept of static variables to share instance across the objects.

Hope this clarifies about class attributes and object attributes.

Community
  • 1
  • 1
Neeraj
  • 551
  • 2
  • 13
0

I believe this is language-specific thing. From the docs

class ClassName:
    <statement-1>
    .
    .
    .
    <statement-N> 

Class definitions, like function definitions (def statements) must be executed before they have any effect. (You could conceivably place a class definition in a branch of an if statement, or inside a function.)

As you can see, these expressions are evaluated and you can even use 'if' statement.

Paul
  • 6,641
  • 8
  • 41
  • 56