Need help passing variables from classes!

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
bschaeffer
Forum Newbie
Posts: 24
Joined: Thu Apr 30, 2009 9:10 pm

Need help passing variables from classes!

Post by bschaeffer »

Hi.

Pretty new to PHP here, and I was wondering why I can't echo out variables from one section of php to the other when the first instance of the variables appear inside a class.

Here's my example class:

Code: Select all

class myClass {
  function myFunction {
   $user_info = array(
      'username' => $result['auth']['user']['username'],
      'fullname' => $result['auth']['user']['fullname'],
   );
  }
}
And this example code is basically what I am trying to do:

Code: Select all

<?php
include 'myClass.php';
 
$class = new myClass();
$class->myFunction();
?>
 
<html>
<head></head>
<body>
 
<?php print_r($user_info); ?>
 
</body>
</html>
I know that I can print the array if I create the new class in the same section of the PHP, but what I don't understand is why I have been able to include a .php file full of variables in the first section and echo them out in the second section of php code.

I guess this boils down to three main questions: Is it possible for me to do this? If so, how? And last, is this method even good practice? Basically, because I am new, I don't know the best method to write clean organized code and I am getting the feeling that this is a bad way to go about it.

Thanks in advance!
Last edited by Benjamin on Thu Apr 30, 2009 9:43 pm, edited 1 time in total.
Reason: Changed code type from text to php.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Need help passing variables from classes!

Post by Christopher »

Code: Select all

class myClass {
  protected $user_info;
 
  // you want to create objects that are useful when instantiated
  // so pass the necessary data to the constructor
  function __construct($result) {
   $this->user_info = array(
      'username' => $result['auth']['user']['username'],
      'fullname' => $result['auth']['user']['fullname'],
      );
  }
 
  function getUserInfo() {
    return $this->user_info;
  }
}
Then use it:

Code: Select all

<?php
include 'myClass.php';
 
$class = new myClass($result);    // you need to get the user auth infor from somewhere
?>
 
<html>
<head></head>
<body>
 
<?php print_r($class->getUserInfo()); ?>
 
</body>
</html>
Classes should be focused on knowing and doing only the small set of things they need to do. In this case the class has to know some details about the data it gets. That means you can't change that data without effecting this class. Better to have an agreed interface like this:

Code: Select all

class myClass {
  protected $user_info;
 
  // you want to create objects that are useful when instantiated
  // so pass the necessary data to the constructor
  function __construct($user) {
   $this->user_info = array(
      'username' => $user->getUsername(),
      'fullname' => $user->getFullname(),
      );
  }
 
(#10850)
User avatar
bschaeffer
Forum Newbie
Posts: 24
Joined: Thu Apr 30, 2009 9:10 pm

Re: Need help passing variables from classes!

Post by bschaeffer »

arborint wrote:

Code: Select all

 
  // you want to create objects that are useful when instantiated
  // so pass the necessary data to the constructor
  function __construct($user) {
   $this->user_info = array(
      'username' => $user->getUsername(),
      'fullname' => $user->getFullname(),
      );
  }
 
First, I want to say thank you very much for you're response. It contained some information I have been looking for all over the internet.

Second... I have seen the code above before but don't fully understand it, especially the __construct($user) snippet or the $this->user_info one. Is that just saying that $user equals the $user_info array...? Another thing I don't understand is the myFunction extends myOtherFunction.... but anyway.

I was wondering if you, or anyone, could recommend a tutorial or book that really explains how to use classes, when and when not to use them, how to organize the information inside them (i.e pass data into them and get it out).

I'm reading PHP Solutions, and it's been pretty helpful, but what I would really like is a book or site or tutorial or any resource on building code correctly, something that explains what's going on, not just example projects.

I appreciate your response. I will try and start using these ideas while I'm learning... maybe I'll understand them better.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Need help passing variables from classes!

Post by Christopher »

bschaeffer wrote:Second... I have seen the code above before but don't fully understand it, especially the __construct($user) snippet or the $this->user_info one. Is that just saying that $user equals the $user_info array...? Another thing I don't understand is the myFunction extends myOtherFunction.... but anyway.
1) __construct() is the function called with an object is created with new. You can pass it any data that the object need to be initialized with.

2) $this->user_info is accessing the user_info property of the class/object. An object is data with a set of functions that can operate only on that data. It is a private namespace of sorts where code is protected from the rest of the program.

3) extends allows to to inherit the methods and properties of another class. If you declare a method or property of the same name as the class you are extending it will override the inherited one. Inheritence allows you to package base functionality separately, but you can still overide it.
bschaeffer wrote:I was wondering if you, or anyone, could recommend a tutorial or book that really explains how to use classes, when and when not to use them, how to organize the information inside them (i.e pass data into them and get it out).

I'm reading PHP Solutions, and it's been pretty helpful, but what I would really like is a book or site or tutorial or any resource on building code correctly, something that explains what's going on, not just example projects.
Recommending books is difficult because different people like different styles. I'd recommend going to a book store and looking through several books to see if one looks clearer to you.

And, of course, ask questions here. Post code you have tried and someone will help you.
(#10850)
User avatar
bschaeffer
Forum Newbie
Posts: 24
Joined: Thu Apr 30, 2009 9:10 pm

Re: Need help passing variables from classes!

Post by bschaeffer »

Ok... so, I've been trying to test my understanding of classes a little bit and still seem to be lost. I'm trying to use some of the code examples arborint gave above, and here's what I've come up with.

My class:

Code: Select all

class auth {
 
    protected $user_info = array(
        'first_name' => 'John',
        'last_name' => 'Smith',
    );
 
    function __construct($user) {
        $this->first_name = $user_info['first_name'];
        $this->last_name = $user_info['last_name'];
    }
 
    function getFirstname() {
        return $this->first_name;
    }   
 
    function getLastname() {
        return $this->last_name;
    }   
} 
And how I'm trying to implement it.

Code: Select all

<?php
 
require 'myclass.php';
 
$auth = new auth($user_info);
 
?>
 
<html>
<head>
</head>
<body>
    <p>My first name is <?php echo $auth->getFirstname(); ?></p>
    <p>My last name is <?php echo $auth->getLastname(); ?></p>
</body>
</html>
The problem is there's no output (and I'm sure some of you are looking at this going "no sh*t, look what you did"). I know this is a simple example, but this is the exact code I'm using and it just proves I have no idea at all about how classes work.
joshmaker
Forum Commoner
Posts: 25
Joined: Mon May 15, 2006 2:53 pm
Location: Arlington VA

Re: Need help passing variables from classes!

Post by joshmaker »

I think the problem here is that you are using arrays when you don't need to. Take a look at this:

Code: Select all

class auth {
 
    protected $first_name;
    protected $last_name;
 
    function __construct($first_name, $last_name) {
        $this->first_name = $first_name;
        $this->last_name = $last_name;
    }
 
    function getFirstname() {
        return $this->first_name;
    }   
 
    function getLastname() {
        return $this->last_name;
    }   
}
 
and then...

Code: Select all

 
<?php
require 'myclass.php';
$auth = new auth('John', 'Smith');
?>
 
<html>
<head>
</head>
<body>
    <p>My first name is <?php echo $auth->getFirstname(); ?></p>
    <p>My last name is <?php echo $auth->getLastname(); ?></p>
</body>
</html>
Also, two quick tips: naming your function Auth may seem look a good idea today, but when you go back to edit this code a month later, I bet you won't know what it is. I would give it a more descriptive name such as "Authenticator" or "User". It is generally a good idea to think of classes as nouns and their functions as verbs. Also, to keep things organized I recommend saving each class in its own file named with the same name as the class it contains.
joshmaker
Forum Commoner
Posts: 25
Joined: Mon May 15, 2006 2:53 pm
Location: Arlington VA

Re: Need help passing variables from classes!

Post by joshmaker »

Another note: If you declare your variables to be public instead of protected then you can access them directly outside of the class like so:

Code: Select all

class User {
    public $first_name;
    public $last_name;
    
    function __construct($first, $last) {
        $this->first_name = $first;
        $this->first_name = $last;
    }
}
 
$john = new User('John', 'Smith');
echo 'Hello, my name is ' . $john->first_name . ' ' . $john->last_name;
HOWEVER, the way that was done in the earlier script was a better way to do it because it gives you more power later on.

For example, if you decided that you always wanted to make sure that the user's name was capitalized before printing it out you could change your function to say:

Code: Select all

function getFirstName() {
    return ucfirst($this->first_name);
}
function getLastName() {
    return ucfirst($this->last_name);
}
 
and then everywhere that you wrote $user->getFirstName() would now always be properly capitalized. If you had used $user->first_name directly you would have a much harder time doing so.
Post Reply