Need basic help constructing a class!

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 basic help constructing a class!

Post by bschaeffer »

I've been posting on my trouble understanding classes here, and figured, if anyone was up for it, that I'd ask for some help building a basic class.

Because I don't really understand classes yet, I might be trying to explain something that's not possible or just down right the hardest way to do something.... but here I go anyway (also, I just want to let you know that I've gotten everything I am describing to work, I just want to clean it up and put it inside a class):
  • I've got an index page with a basic link on it. The user clicks the link, gets sent to another page to verify access, then comes back with some data.
  • Next, I want to take the data they come back with, generate a signed request for a token, request the token, and, just for testing and to make sure it worked, echo the token.
  • I've got a list of constant variable stored in a php file I am including, also, but that list needs to make it inside the classes.
Again, I've got the code right that makes this work, I just don't know how to implement it into a class. I'd like to be able to run the class at the beginning of the html document, load the html, then echo out the results inside the body of the html file.

I know this is a lot to ask, but I am really having a hard time understanding how I would do this, how to use __construct, how to return variables that are available to be echoed out where I want them.

Any input would be greatly, greatly, tremendously appreciated. I'll be on my aim if anyone feels bored and wants to help.

Again... thanks in advance.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Need basic help constructing a class!

Post by Christopher »

Is it possible for you to post a super simpified version of your code that others could actually run? The output can be minimal. It sounds like a couple of PHP pages. The reason I ask is that you are talking about a lot of implementation details, but not much about the design. It also may not me one class.
(#10850)
User avatar
bschaeffer
Forum Newbie
Posts: 24
Joined: Thu Apr 30, 2009 9:10 pm

Re: Need basic help constructing a class!

Post by bschaeffer »

Sure. Here is the entire code because believe it or not, simplifying it is giving me a headache.

My include file.

Code: Select all

<?php
 
// A bunch of variables would be here, then I turn them into an array
 
$authorize_info = array(
    'api_key' => $api_key,
    'secret' => $secret,
    'signature' => $sig,
    'api_sig' => $api_sig,
    'format' => $format,
    'frob' => $frob,
);
 
?>
My class file (might be a little mucked up because I've been fiddling with it, but all that's important is that you see all the stuff I'm trying to do and how I'd like to make certain data available to me later in the page instead of having to echo it out in the class):

Code: Select all

<?php
 
class Authorize {
 
    protected $authorize_info
    
    function __construct($user) {
        $this->authorize_info = array (
            'api_key' => $api_key,
            'format'=> $format,
            'frob' => $frob,
            'method' = $method,
        );
        
    }
    
    function getToken($user) {
    
        $method = 'flickr.auth.getToken';
    
        $getTokenParams = array(
            'api_key' => $this->user['api_key'],
            'format' => $this->user['format'],
            'frob' => $this->user['frob'],
            'method' => $this->user['method'],
        );
 
        // I would do a bunch of stuff with this array to make a url that will make the call
        
        $url = 'http://somewebsite.com/?'.implode('&', $c_params).'&api_sig='.$api_sig;
        $response = file_get_contents($url);
        $result = unserialize($response);
 
        // Then, I want to be able to just make the call, get the data
        // and use the result later in another class function
        return $result;
    }
    
}
    
class userInfo extends Authorize {
 
    $result;
 
    function getUserInfo($this->result) {
        
        $user_info = array(
            'token' => $result['auth']['token']['_content'],
            'perms' => $result['auth']['perms']['_content'],
            'user_id' => $result['auth']['user']['nsid'],
            'username' => $result['auth']['user']['username'],
            'fullname' => $result['auth']['user']['fullname'],
        );
        
        // I'd like to use this for later, too, without having to make another call
        // just to get the same data I already had
        return $user_info;  
    }
        
}
 
?>
Then I want to do something like this:

Code: Select all

<?php
include 'my_include.php';
 
$authorize = new Authorize();
$user = new userInfo();
 
?>
<html>
<head></head>
<body>
<p>Heres my call url: <?php $authorize->getToken($user); ?></p>
<p>Heres your user info: <?php $user->getUserInfo($result); ?></p>
</body>
</html>
 
I've just confused myself so much I don't even know if what I was doing right before is working and I'm starting to think that I don't even want to use classes even though it would make it easier to reuse code over and over again.

Does this make any sense, because if it doesn't then I'll just forget about it until I just have to learn it.
mickd
Forum Contributor
Posts: 397
Joined: Tue Jun 21, 2005 9:05 am
Location: Australia

Re: Need basic help constructing a class!

Post by mickd »

I just had a brief look at your classes, and there seems to be a lot of errors in the code.

When you make your class (this is just an example):

Code: Select all

 
<?php
 
class Authorize {
 
   private $user;
 
   public function __construct($user) {
   // to use use $user later in your object, you need to save it somewhere, for example
   $this->user = $user;
 
   }
 
   public function getToken() {
   // if you've saved $user already (from the constructor), you don't need to pass it in again.
   // to use user, you would do, for example
   $this->user->getUserInfo();
 
   // if you haven't saved $user yet, or if you want to pass it into getToken($user)
   // to use user, you would do this, for example
   $user->getUserInfo();
 
   }
 
}
 
?>
 
Basically, what I'm trying to show you is, you only use $this-> IF you are calling a variable or function in that class while you are in that class.

Code: Select all

 
<?php
 
class Foo {
 
   public $bar;
 
   public function __construct($value) {
 
   $this->bar = $value;
 
   }
 
   public function changeBar($value) {
 
   $this->bar = $value;
 
   }
 
   public function displayBar() {
 
   echo $this->bar;
 
   }
 
}
 
$foo = new Foo('one');
$foo->displayBar();
// echos out one
$foo->changeBar('two');
// echos out two
 
?>
 
Watch the syntax used while inside the class to call its own members/methods.

Hope that helps.
User avatar
bschaeffer
Forum Newbie
Posts: 24
Joined: Thu Apr 30, 2009 9:10 pm

Re: Need basic help constructing a class!

Post by bschaeffer »

Ohhhhhhhh........

I see, that last example you gave kind of made it clear. I think, now, if I just start from scratch I'll be able to see how this is working.

I think I get it now.. wondering if it should have been this confusing or if I am just an idiot.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Need basic help constructing a class!

Post by Christopher »

bschaeffer wrote:I think I get it now.. wondering if it should have been this confusing or if I am just an idiot.
Nope ... join the club ... and keep asking questions ... ;)
(#10850)
User avatar
bschaeffer
Forum Newbie
Posts: 24
Joined: Thu Apr 30, 2009 9:10 pm

Re: Need basic help constructing a class!

Post by bschaeffer »

Just a quick update and one question...

First... I think I am beginning to understand classes pretty well. So far, I've gotten one class function to make and API call, get some data and return the results. Then, I've been able to successfully run another class function which uses those same results. May not seem like a big deal, but it took me forever to understand it. Just wanted to say that.

On that note, my question is about the __constructor function. I am really wondering why and when it is necessary.

I guess a better question is what's the difference between this...

Code: Select all

class Foo { 
  public $bar
  function __construct($value) {
    $this->bar = $value; 
  }
  function displayBar(){
    return $this->bar;
  } 
  function changeBar($value) {
    $this->bar = $value;
    return $this->bar;
  }
}
 
$class = new Foo('one');
 
echo $class->displayBar();
// echos "one"
echo $class->changeBar('two');
// echos "two"
and this?...

Code: Select all

class Foo {
 
  function displayBar($value){
    return $value;
  }
 
}
 
$class = new Foo('one');
 
echo $class->displayBar('one');
// echos "one"
echo $class->displayBar('two');
// echos "two"
Why would you need to construct a variable at all? I know there has to be a reason too, but I just can't see one?
User avatar
Gabriel
Forum Commoner
Posts: 41
Joined: Wed May 06, 2009 8:12 pm
Location: Las Vegas

Re: Need basic help constructing a class!

Post by Gabriel »

__construct is a function recognized by PHP and is called immediately after your class is instantiated. This allows you to execute some code when the class is loaded. Along with that is __destruct which is executed when the class variable is unset, or when the script ends.
mickd
Forum Contributor
Posts: 397
Joined: Tue Jun 21, 2005 9:05 am
Location: Australia

Re: Need basic help constructing a class!

Post by mickd »

There are a lot of things that OOP can help you do that you can't do easily or at all without.

With the 2 examples you gave, the second example completely misses out out on the purpose of having a class.

I'll have a go at trying to enlighten you :)

Code: Select all

 
class Person {
   private $name;
   private $friends = array();
 
   public function __construct($name) {
      $this->name = $name;
   }
 
   public function addFriend($person) {
       $this->friends[] = $person;
   }
 
   public function getName() {
      return $this->name;
   }
 
   public function displayFriends() {
      foreach($this->friends as $friend) {
         echo $friend->getName().'<br />';
      }
   }
}
 
$me = new Person('Mick');
$you = new Person('Bschaeffer');
$me->addFriend($you);
$me->displayFriends();
// prints out Bschaeffer
$you->displayFriends();
// prints out nothing atm
$gabriel = new Person('Gabriel');
$you->addFriend($gabriel);
$you->displayFriends();
// prints out Gabriel
 
 
Kind of a cheesy example, i know. But, with what you did before, you can't easily create multiple instances of "Foo", which can be all different (like the different people), and have their own 'variables' associated to them.

Hope this kind of helps!
User avatar
bschaeffer
Forum Newbie
Posts: 24
Joined: Thu Apr 30, 2009 9:10 pm

Re: Need basic help constructing a class!

Post by bschaeffer »

I really appreciate those examples. I've taken some of those ideas and just ran with them in my own experimental projects, and they have really helped.

On that note, just working with classes has opened up some new questions, but they are a little bit simpler to explain, I think.

I've got four (I keep adding them as I type) of them:

1. When you create a class that extends another class, does the __construct function from the parent run, or does that only happen inside the class doing the extending? Or do they both run?

2. Are the $this-> variables from the parent class available to the extending class? How do you call them?

3. Does everything work the same inside classes? For instance, if I include php file full of variables inside a class, can I call them just like I would if I was outside a class?

Example:

Code: Select all

 
//The included file
<?php 
$name = 'john';
?>
 
// Regular (if that's a good way to describe it)
<$php
include 'myfile.php';
echo $name;
?>
 
// In a class
<?php
class myClass {
  include 'myfile.php'
  function __construct() {
    $this->name = $name;
  }
}
?>
 
4. Is extending a class more useful than calling one class from another? Can you call one class from inside another?

I think that's all the questions I have. I think they are much more easily understood than some of the previous ones I've been throwing at you.

Anyway, I just want to say that you all have been really, really great and I wanted to thank everyone for taking the time to read this posts and answer my noob questions.

And thanks in advance for helping me out with these new ones.
mickd
Forum Contributor
Posts: 397
Joined: Tue Jun 21, 2005 9:05 am
Location: Australia

Re: Need basic help constructing a class!

Post by mickd »

Glad i was able to help :)

1. When you extend another class, if there is a constructor for the child, it will only run that. If the child doesn't have a constructor, it will run the parent's constructor.

Code: Select all

 
<?php
 
class Mother {
 
    public $name;
    
    public function __construct($name) {
    
       $this->name = $name;
        echo 'Parent constructor!!<br />';
    }
}
 
class Child extends Mother {
 
    public function __construct($name) {
    
        $this->name = $name;
        echo 'Child constructor!!<br />';
    }
}
 
class ChildTwo extends Mother {
 
    
}
 
// what it prints out in the comments below:
$mother = new Mother('joan');
// Parent constructor!!
$child = new Child('john');
//Child constructor!!
$childTwo = new ChildTwo();
// a warning that you're missing an argument and it echos
// Parent constructor!!
$childTwo = new ChildTwo('john');
// Parent constructor!!
 
?>
 
2. Yep, everything from the parent (if it wasn't overwritten in the child), is available in the child. Using the same example classes above,

Code: Select all

 
// childTwo class is the one that has nothing in it
$childTwo = new ChildTwo('john');
$childTwo->name = 'mick';
echo $childTwo->name;
// prints mick
 
And to call a parent function/variable from a child class, you would still just use $this->

3. You can't include a file in the top of a class (like in the example), but technically, you could inside a function in a class. This seems kind of weird to me, i don't think i ever had to do it that way, and chances are there's a better way (but I'll need to see the situation in which you use it).

4. Yep, you can call one class from inside another, but only if you have given (or that class can access) the object from inside the class.

Code: Select all

 
<?php
class Foo {
 
    public function printSomething() {
    
        echo 'Another class!<br />';
    }
}
 
class Test {
 
    public $anotherClass;
    
    public function __construct($anotherClass) {
    
        $this->anotherClass = $anotherClass;
    }
    
    public function useClass() {
    
        return $this->anotherClass;
    }
 
}
 
$foo = new Foo();
$test = new Test($foo);
$test->useClass()->printSomething();
// prints Another class!
 
?>
 
A trivial example, but i hope it helps :)
Post Reply