Jump to content

basic constructor question


tulley

Recommended Posts

experienced C++, new to php, question:

 

I am following the tutorial at killerphp, using the following code..

 

<?php

class person {

var $name;

function __construct($persons_name) {

$this->name = $persons_name;

}

function set_name($new_name) {

$this->name = $new_name;

}

function get_name() {

return $this->name;

}

}

?>

 

and...

 

<?php

$stefan = new person("Stefan");

 

echo "Stefan's full name: " . $stefan->get_name();

?>

 

The echo statement does not print the name set by the constructor. It works fine when using a set_name() function. What am I missing?

 

I think I'm using version 4.x? of php.

Link to comment
Share on other sites

"__construct" is something that is new to PHP5, so if you are running php 4, you won't be able to use it. This doesn't mean you can't use Object Oriented programming at all with PHP4, you just have to do it a different way:

 

    class person {
       var $name;
       function person($persons_name) {       
           $this->name = $persons_name;       
       }       
       function set_name($new_name) {
             $this->name = $new_name;
       }   
       function get_name() {       
             return $this->name;       
        }       
   }

   $stefan = new person("Stefan");       
   echo "Stefan's full name: " . $stefan->get_name();        
?>

 

With PHP4, you can't use "__construct", your constructor needs to be the same name as the class (in this case, "function person").

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...