Say I have a class that looks like this:


<?php

class User () {

var $varName, 
$varName2 = " varValue2";

function User () {

$this -> varName = " varValue ";

}

function MyMethod () {
// do stuff for MyMethod
}

}

?>

Whats the point of the function / method User()? What is it supposed to do and why is it always in every class I see, and why is it alwasy used to set a variable equal to a value, when I can just set its value when I initialize it with var $varName?

Thanks!

    a try:

    the constructor is the first executed function of a class.
    making a new object...

    $view = new MyView();

    ...you call the constructor MyView() of the class MyView indirectly.
    the constructor can be used to set certain variables to certain values, or even call another object or another constructor.

    class MyView{
    
    var $obj_view;
    
     /* this constructor sets the class variable $this->obj_view
     * to $value, which is defined when calling the object by:
     * $anyView = new MyView($value); */
     function MyView($view){
     $this->obj_view = $view;
     }
    
     /* if the constructor would not 'predefine' $obj_view,
     * this function would print out nothing */
     function printView(){
     print($this->obj_view);
     }
    
    }

    to make an object of this class you can go:

    $anyView = new MyView("Landscape");
    $anyView->PrintView();
    

    instead of using the constructor you could also write a function for that on your own, here: function initVariable()

    class My View{
    
    var $obj_view;
    
     function MyView(){
     // does nothing
     }
    
     function initVariable($view){
     $this->obj_view = $view;
     }
    
     function printView(){
     print($this->obj_view);
     }
    
    }
    

    calling the object the difference is, you do 1 call more.

    $anyView = new MyView();
    $anyView->initVariable("Landscape");
    $anyView->printView();
    

    both, the constructor in example 1 and the function initVariable() do nothing but set var $obj_view (or any other class variable) to a certain value in order to be able to work with it in a later function [here: printView()]. without them the function would print out nothing as there is no value assigned to $obj_view.

    i would suggest to use the constructor-way, as its shorter and probably easier to handle when inheriting from classes...

    please anyone, correct me if i am wrong.

      Originally posted by crosbystillsnas
      the constructor can be used to set certain variables to certain values, or even call another object or another constructor.

      An example of this latter use is if your class extends another; unlike Java, you'd need to call the parent class's constructor explicitly if you want it:

      class MyClass extends ParentClass{
      ...
      function MyClass()
      {   $this->ParentClass();
          ...
      }
      ...
      }

        So... basically a Constructor is used to initialize variables to a NON-STATIC value ( I see no value of using it to initialize static values, cause you can do that when you declare the vars in your var $varname statement. )

        OR

        To call another object or method when the current object is created.

        Yes? Is this pretty much the case across all languages out of curiosity? Any other purposes?

          Originally posted by superwormy
          So... basically a Constructor is used to initialize variables to a NON-STATIC value ( I see no value of using it to initialize static values, cause you can do that when you declare the vars in your var $varname statement. )

          OR

          To call another object or method when the current object is created.

          Yes? Is this pretty much the case across all languages out of curiosity? Any other purposes?

          Constructors only apply to objects. The same goes for C++, Java, etc. Constructors are functions just like any other, except they are called when an object is instantiated, or created. It is very useful in that you can initialize variables for your object, call other functions, etc. Static variables simply hold strings or numbers and do not have constructors.

            You use a constructor so the value of the object is known at all times. There are no points where you should get an unknown value. It has to do with the way memory is managed. When other programs stop using memory, they do not clear the contents. So it is very easy to get a bunch of jibberish when your program allocates blocks of memory.

              Goobster, yes, I realize they're only for objects, read the rest of the post.

              Ravenous, I understand that they can initialize variables... BUT, WHY NOT JUST INITILIZE VARIABLES WHEN YOU DECLARE THEM?!?

              Whats the difference between doing this:

              
              <?php
              
              class MyClass {
              
              var $var;
              
              function MyClass () {
              $this -> var = "value";
              }
              
              }
              
              ?>
              
              

              And this:

              
              <?php
              
              class MyClass {
              
              var $var = "value";
              
              function MyClass () {
              
              }
              
              }
              
              ?>
              
              

              They both initialize taht variable on instantiation of the object, right?

                Yes.. they both initialize the value. All I can tell you is that constructors (and destructors) are the accepted (standard?) way of doing things. I can't give you a super-specific answer. All I know is that those with many years more programming experience than I use them. So there must be a reason. 😃

                  superwormy, if you have a class 'car' this becomes clear.

                  class car{
                  
                  var $color;
                  
                   function car($color){
                   $this->color = $color;
                   }
                  
                   function tellMeTheColorOfTheCar(){
                   print($this->color);
                   }
                  
                  }
                  

                  we can make 3 cars of 1 class:

                  $red_car = new car("red");
                  $blue_car = new car("blue");
                  $green_car = new car("green");

                  to make these 3 cars using your second method, you would need 3 classes.

                    RIGHT, I REALIZE THAT, THAT'S WHY I STATED BEFORE, FOR NON-STATIC VALUES:

                    So... basically a Constructor is used to initialize variables to a NON-STATIC value ( I see no value of using it to initialize static values, cause you can do that when you declare the vars in your var $varname statement. )

                    Now, I ask AGAIN:

                    So... basically a Constructor is used to initialize variables to a NON-STATIC value ( I see no value of using it to initialize static values, cause you can do that when you declare the vars in your var $varname statement. )

                    OR

                    To call another object or method when the current object is created.

                    Yes? Is this pretty much the case across all languages out of curiosity? Any other purposes?

                      Originally posted by superwormy
                      RIGHT, I REALIZE THAT, THAT'S WHY I STATED BEFORE, FOR NON-STATIC VALUES:




                      Now, I ask AGAIN:

                      So... basically a Constructor is used to initialize variables to a NON-STATIC value ( I see no value of using it to initialize static values, cause you can do that when you declare the vars in your var $varname statement. )

                      OR

                      To call another object or method when the current object is created.



                      Yes? Is this pretty much the case across all languages out of curiosity? Any other purposes?

                      yes. take caps off and stop flaming ppl that are trying to help you

                        Originally posted by superwormy
                        Now, I ask AGAIN:

                        Gee, why are you sounding so desperate - you got a school assignment or something? 🙂

                        Constructors are used to construct objects from classes, hence the name. What more do you want? Laundry services?

                        As for whether it's the same across langauges - it depends entirely on the language. Some languages don't even have variables, let alone objects.

                          if you got to create more than 100 classes in your application, why don't just make it procedural code.

                          OOP and its constructor just a way to manage code.
                          they don't really help IMHO. 🙂

                            All I wanted was to know if constructors did anything else besides initialize variables to non-static values and / or call other objects.

                            Do they do anything else besides that?

                            So far crosbystillsnas has posted a useless thing without reading previous posts, g00bster has explained to me that they only apply to objects, which I knew, hence the title of the tread, OOP Question..., and now jimson is going totally off topic and telling me about how its better to just use procedural code.

                            Don't you find that frustrating when half the posts to your topic are entirely off-topic or posted without people actually reading your question?

                              The only thing that other functions/methods can do that you cannot do with a constructor is to return a value.

                              For example, code in the constructor could easily open a connection to a database, query some records, perform some calcs and output some html code.

                              In fact, most of my scripts have one master script object. I just create one of these objects and let it run. This object in turn creates many other helper objects which contain most of the actual code.

                                i thought i already answered u... well... ok..

                                Whats the point of the function / method User()?
                                << it functions as class constructor.

                                What is it supposed to do
                                << people use it to initialize variable and its values.
                                << some also use it to run a function / method whenever the object is initialized with new User();

                                Why is it always in every class I see
                                << because every people have a different way of initializing variables and it values or u might want to say attributes. It also depend on the application scale.

                                why is it alwasy used to set a variable equal to a value
                                << because this is one of the constructor's function

                                when I can just set its value when I initialize it with var $varName?
                                << like i said before, unless u are in the medium large size application. people get confused when they have thousand of class and they want the class to have a same attributes.

                                $a = new user();
                                $a->type = 'user';
                                
                                $b = new user();
                                $b->type = 'user';
                                
                                $c = new user();
                                $c->type = 'user';
                                
                                /*
                                if u got thousand classes, u will find it stupid to do same things 
                                again and again. thats why there is a need of constructor. so u 
                                just need to declare the variable and no worry about being 
                                confused or forget to initialize the user object with attribute type 
                                ='user' whenever u declared it...
                                */
                                

                                like i said before.

                                OOP and its constructor just a way to manage code.
                                they don't really help IMHO. 😉

                                  A constructor in a class will do whatever you need to have happen when your program creates an instance of a class. This may include initializing variables, opening database connections, or whatever.

                                  Keep in mind when you create an instance of a class in your code, you may immediately try to read a property variable of the class and if the variable hasn't been initialized properly you'll get some garbage or an error back to your program.

                                  Hopefully classes in PHP5 will include some of the currently missing features that should be there, particularly private functions and variables that aren't exposed by an instance of the class.

                                  I'd like to see a destructor also.

                                    Originally posted by Doug G
                                    Hopefully classes in PHP5 will include some of the currently missing features that should be there, particularly private functions and variables that aren't exposed by an instance of the class.

                                    I'd like to see a destructor also.

                                    From what I've seen of the beta, it does; along with things like class constants, which is nice.

                                      Originally posted by jimson
                                      OOP and its constructor just a way to manage code.
                                      they don't really help IMHO. 😉

                                      You've also said before that you don't have much experience, so it's a bit early for you to be getting religously anti-OO.

                                      If I want to read from an object with a read() method, I don't want to have to care whether it's reading from a file or an array or a resource or a device or its navel; I just $object->read(). Let the object figure out how read() is supposed to work. And I'm ralfed if I'm going to rewrite read() every time I come up with a new source to read from.

                                      But, as superwormy pointed, this is off-topic.

                                        So... basically a Constructor is used to initialize variables to a NON-STATIC value ( I see no value of using it to initialize static values, cause you can do that when you declare the vars in your var $varname statement. )

                                        That isn't exactly true (at least in PHP4).

                                        Another thing to consider is that (as hard as it tries) PHP isn't really an OO language. Heck, this whole type juggling system dosn't lend itself to strict derivation and whatnot very well at all.

                                        Constructors and destructors serve a purpose in more fully object oriented langauges. C++, and it's dynamic memory allocation scheme, is an excellent example.

                                        You need to be able to get an object 'ready' to play with the rest of your code by allocating memory and whatnot, depending on the circumstance. That's all handled by the constructor. Where would your favorite vector class be if it were uninitialized?

                                        Likewise, you must explictly free memory that you've allocated. This would be very inconvienet if you had to write and call your own functions every time an object went out of scope. If you forgot, you would be left with any number of memory leaks, and one hell of a debugging problem. To save you C++ provides the destructor, which is gaurnteed to be called when your object goes out of scope. It's essentailly a cleanup function.