TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old 07-13-2008, 08:25 PM   #1 (permalink)
The Acquainted
Upcoming Programmer 
 
CMellor's Avatar
 
Join Date: Sep 2007
Location: Leeds, UK
Posts: 141
Thanks: 6
CMellor is on a distinguished road
Default My First Class - Any Good?

Hey,

I've never coded using PHP 5's OOP, and while I was planning a new project, I knew I was going to be using it, as well as using the MySQLi function. I've read loads of stuff now on OOP and I think I've got the hang of it, sorta, but at a newbie stage... ya know? lol

I whipped up this code, I just want you to tell me what I did right and wrong and how it can be improved:

PHP Code:
<?php
class math {

    const 
host 'localhost';
    const 
user 'root';
    const 
pass 'blergh';
    const 
db 'project';
    
    public function 
__construct() {
        
// Start MySQLi connection
        
$mysqli = new mysqli(self::hostself::userself::passself::db);
        
// Check if connect
        
if(mysqli_connect_errno()) {
            throw new 
exception('MySQLi did not connect');
        }
    }
        
    public function 
plus($x$y) {
        
$this->$x;
        
$this->$y;
        
        return 
$this->$this->y;
    }

}

$class = new math;

try {
    echo 
$class->plus(2255);
}
catch(
exception $e) {
    echo 
$e->getMessage();
}

?>
Cheers!
__________________
Not quite a n00b...
CMellor is offline  
Reply With Quote
Old 07-13-2008, 09:54 PM   #2 (permalink)
The Acquainted
 
drewbee's Avatar
 
Join Date: May 2008
Posts: 175
Thanks: 9
drewbee is on a distinguished road
Default

It is a good start! A few things:

You dont have the class instance variables x and y defined.

Code:
$this->x = $x;
$this->y = $y;
Below your database constant variables, put this
PHP Code:
var $x;
var 
$y
Now your assignments above can actually place these variables, and if you wanted to access what you recently put through the last function call:

PHP Code:
$class = new math;

try {
    echo 
$class->plus(2255);
    echo 
'We added ' $class->' + ' $class->y;
}
catch(
exception $e) {
    echo 
$e->getMessage();
}

?> 

MysqlI rules, doesn't it? :D

PHP Code:
$db = new mysqli('localhost''user''pass''database');
$query $db->query("SELECT col1, col2, col3 FROM table WHERE foo = 'bar'");

if (
$query->num_rows 0)
{
    while (
$row $query->fetch_array())
    {
        echo 
$row['col1'] . ' ' $row['col2'] . ' ' $row['col3'];
     }
}
else
{
    echo 
'no records found';

__________________
There are No Stupid Questions. But there a LOT of Inquisitive Idiots.
Send a message via AIM to drewbee
drewbee is offline  
Reply With Quote
Old 07-13-2008, 10:13 PM   #3 (permalink)
is cute and cuddly
 
delayedinsanity's Avatar
 
Join Date: Mar 2008
Location: Vegas, Baby
Posts: 963
Thanks: 31
delayedinsanity is on a distinguished road
Default

Quote:
Now your assignments above can actually place these variables, and if you wanted to access what you recently put through the last function call:
Actually, since PHP supports dynamic properties, once they are set, they are accessible either way. So you don't necessarily have to define every property you plan on using, it's just good practice. Take the following for example;

PHP Code:
class var_test
{

    public function 
set ($x$y)
    {
        
$this->$x;
        
$this->$y;
    }

    public function 
show ()
    {
        echo 
'X: <strong>',$this->x,'</strong><br />';
        echo 
'Y: <strong>',$this->y,'</strong><br />';
    }

    public function 
add ()
    {
        echo 
$this->x,'+',$this->y,'=',$this->x+$this->y;
    }

};

$pTest = new var_test;
$pTest->show();
$pTest->set(1010);
$pTest->show();
$pTest->add();
echo 
'<br />',$pTest->x
The first call to show() will return Notice: Undefined property: var_test::$x in...but the second time it works as the properties have been set, even though they were not laid out in the class.
-m
delayedinsanity is offline  
Reply With Quote
Old 07-13-2008, 11:17 PM   #4 (permalink)
The Acquainted
 
drewbee's Avatar
 
Join Date: May 2008
Posts: 175
Thanks: 9
drewbee is on a distinguished road
Default

Yeah :) I am more about pushing good standards before they start making poor programming standards.

I wish PHP was more strict in this area, heh.
__________________
There are No Stupid Questions. But there a LOT of Inquisitive Idiots.
Send a message via AIM to drewbee
drewbee is offline  
Reply With Quote
Old 07-13-2008, 11:45 PM   #5 (permalink)
is cute and cuddly
 
delayedinsanity's Avatar
 
Join Date: Mar 2008
Location: Vegas, Baby
Posts: 963
Thanks: 31
delayedinsanity is on a distinguished road
Default

I'm glad it's not. As I mentioned, and as you said, it is good practice to define properties that you are going to need, and in a lot of cases it's even better practice to make sure those properties are intialized to some degree in your construct or any method that needs them.

That being said, there are situations where using a dynamic property can be an asset. If you want, you can even use the built in magic functions so that any dynamic variables you plan on using will exist inside of a defined property, like so;

PHP Code:
class dynamic_properties
{
    private 
$dynamic = array();

    public function 
display_library ()
    {
        echo 
'<pre>';
        
print_r($this->dynamic);
        echo 
'</pre>';
    }

    public function 
__set($szName$szValue)
    {
        
$this->dynamic[$szName] = $szValue;
    }

    public function 
__get($szName)
    {
        if (isset(
$this->dynamic[$szName]))
            return 
$this->dynamic[$szName];
    }
    
    public function 
__isset($szName)
    {
        return isset(
$this->dynamic[$szName]);
    }
    
    public function 
__unset($szName
    {
        unset(
$this->dynamic[$szName]);
    }

};

$pDynamic = new dynamic_properties;
$pDynamic->var1 'Hello, ';
$pDynamic->var2 'world!';

echo 
$pDynamic->var1,$pDynamic->var2,'<br />';

$pDynamic->display_library(); 
A zen buddhist once said, "There are as many ways to the one as there are people."
-m
delayedinsanity is offline  
Reply With Quote
Old 07-14-2008, 01:15 AM   #6 (permalink)
The Acquainted
Upcoming Programmer 
 
CMellor's Avatar
 
Join Date: Sep 2007
Location: Leeds, UK
Posts: 141
Thanks: 6
CMellor is on a distinguished road
Default

I thought we didn't use var anymore? I'm using PHP 5. Isn't it:

PHP Code:
public $x
public $y 
???
__________________
Not quite a n00b...
CMellor is offline  
Reply With Quote
Old 07-14-2008, 01:46 AM   #7 (permalink)
is cute and cuddly
 
delayedinsanity's Avatar
 
Join Date: Mar 2008
Location: Vegas, Baby
Posts: 963
Thanks: 31
delayedinsanity is on a distinguished road
Default

Yeah, var is php4 OOP. With PHP5 you set visibility with the public, private and protected keywords.
-m
delayedinsanity is offline  
Reply With Quote
Old 07-14-2008, 08:33 AM   #8 (permalink)
The Prestige
Advanced Programmer Top Contributor Good Samaritan 
 
sketchMedia's Avatar
 
Join Date: Oct 2007
Location: Manchester, UK
Posts: 854
Thanks: 32
sketchMedia is on a distinguished road
Default

yes using var is deprecated and removed completely in php6 i think.
__________________
mysql> SELECT * FROM `users` WHERE `users`.`clue` > 0;
Empty set (0.00 sec)
sketchMedia is offline  
Reply With Quote
Old 07-14-2008, 12:11 PM   #9 (permalink)
The Prestige
Upcoming Programmer Inquisitive 
 
Tanax's Avatar
 
Join Date: Sep 2007
Location: Sweden, Stockholm
Posts: 1,080
Thanks: 115
Tanax is on a distinguished road
Default

Why are you using self::$localhost and self:: all over the place?
If you're using PHP5, then you have use a static variable, and you aren't, so.. you need to use $this->localhost etc.
__________________
Tanax is offline  
Reply With Quote
Old 07-14-2008, 12:41 PM   #10 (permalink)
The Frequenter
Newcomer 
 
xenon's Avatar
 
Join Date: Dec 2007
Location: Bucharest, Romania
Posts: 438
Thanks: 3
xenon is on a distinguished road
Default

Because you can't access class constants and/or static properties using the $this keyword.
__________________
I have optimistic thoughts, even though sometimes (if not always) life's a bitch.
xenon is offline  
Reply With Quote
Old 07-14-2008, 12:59 PM   #11 (permalink)
The Acquainted
 
drewbee's Avatar
 
Join Date: May 2008
Posts: 175
Thanks: 9
drewbee is on a distinguished road
Default

Quote:
Originally Posted by sketchMedia View Post
yes using var is deprecated and removed completely in php6 i think.
Man are you serious? Thats annoying. lol. Looks like its time for some code re-write.
__________________
There are No Stupid Questions. But there a LOT of Inquisitive Idiots.
Send a message via AIM to drewbee
drewbee is offline  
Reply With Quote
Old 07-14-2008, 03:26 PM   #12 (permalink)
The Acquainted
Upcoming Programmer 
 
CMellor's Avatar
 
Join Date: Sep 2007
Location: Leeds, UK
Posts: 141
Thanks: 6
CMellor is on a distinguished road
Default

Quote:
Originally Posted by Tanax View Post
Why are you using self::$localhost and self:: all over the place?
If you're using PHP5, then you have use a static variable, and you aren't, so.. you need to use $this->localhost etc.
Quote:
Originally Posted by xenon View Post
Because you can't access class constants and/or static properties using the $this keyword.
Urm, yeah, what he said ^

I'd always used define and remembered once I saw a different way of doing that with OOP, ala const so seeing as I love being different, I did it that way :P
__________________
Not quite a n00b...
CMellor is offline  
Reply With Quote
Old 07-14-2008, 03:31 PM   #13 (permalink)
The Acquainted
 
drewbee's Avatar
 
Join Date: May 2008
Posts: 175
Thanks: 9
drewbee is on a distinguished road
Default

Quote:
Originally Posted by CMellor View Post
Urm, yeah, what he said ^

I'd always used define and remembered once I saw a different way of doing that with OOP, ala const so seeing as I love being different, I did it that way :P
Though what you do is correct. Constants are usually accessed through the self:: or ClassName:: while properties (public variables) are accessed through $this.

I've seen some really funky stuff going along with inheritance and constants though so I stayed away from them :D
__________________
There are No Stupid Questions. But there a LOT of Inquisitive Idiots.
Send a message via AIM to drewbee
drewbee is offline  
Reply With Quote
Old 07-14-2008, 03:32 PM   #14 (permalink)
The Acquainted
Upcoming Programmer 
 
CMellor's Avatar
 
Join Date: Sep 2007
Location: Leeds, UK
Posts: 141
Thanks: 6
CMellor is on a distinguished road
Default

Sorry for the double post!

Is it good coding to put the MySQL connection inside the __construct function?

Also I tried doing:

PHP Code:
public function __destruct() {
    
mysqli_close();

But I got errors :\
__________________
Not quite a n00b...
CMellor is offline  
Reply With Quote
Old 07-14-2008, 03:38 PM   #15 (permalink)
The Acquainted
 
drewbee's Avatar
 
Join Date: May 2008
Posts: 175
Thanks: 9
drewbee is on a distinguished road
Default

Well, since this is a math class, I would actually have a seperate class for the database as well
PHP Code:
class Math
{
    public 
mysqli;
 
    public function 
__construct()
    {
          
$this->mysqli = new mysql('local','user','pass','db');
    }
}
 
$math = new Math;
$math->mysqli->query("SELECT...."); 
__________________
There are No Stupid Questions. But there a LOT of Inquisitive Idiots.
Send a message via AIM to drewbee
drewbee is offline  
Reply With Quote
The Following User Says Thank You to drewbee For This Useful Post:
CMellor (07-14-2008)
Old 07-14-2008, 04:27 PM   #16 (permalink)
The Prestige
Advanced Programmer Top Contributor Good Samaritan 
 
sketchMedia's Avatar
 
Join Date: Oct 2007
Location: Manchester, UK
Posts: 854
Thanks: 32
sketchMedia is on a distinguished road
Default

Static methods/variables and class constants are bound to the class therefore we must use self to reference the current class, $this however references the current object not class, remember there is a fundamental difference between the two; that is why you can't use $this to access methods/properties marked as static or class constants because they are bound to the class not the object.
__________________
mysql> SELECT * FROM `users` WHERE `users`.`clue` > 0;
Empty set (0.00 sec)
sketchMedia is offline  
Reply With Quote
The Following User Says Thank You to sketchMedia For This Useful Post:
drewbee (07-14-2008)
Old 07-14-2008, 04:35 PM   #17 (permalink)
The Prestige
Upcoming Programmer Inquisitive 
 
Tanax's Avatar
 
Join Date: Sep 2007
Location: Sweden, Stockholm
Posts: 1,080
Thanks: 115
Tanax is on a distinguished road
Default

Hm, weird.. well if I were you I would use private $localhost instead of constants
__________________
Tanax is offline  
Reply With Quote
Old 07-14-2008, 05:00 PM   #18 (permalink)
The Acquainted
 
drewbee's Avatar
 
Join Date: May 2008
Posts: 175
Thanks: 9
drewbee is on a distinguished road
Default

Quote:
Originally Posted by sketchMedia View Post
Static methods/variables and class constants are bound to the class therefore we must use self to reference the current class, $this however references the current object not class, remember there is a fundamental difference between the two; that is why you can't use $this to access methods/properties marked as static or class constants because they are bound to the class not the object.
Thanks for that explanation. I havn't used method / variable scoping to much yet, and this makes sense.

I guess my real question is, what is the purpose to making a static method vs public? I understand private, protected, and public, but not static.

edit:
Declaring class members or methods as static makes them accessible without needing an instantiation of the class.

More on visibility:
The visibility of a property or method can be defined by prefixing the declaration with the keywords: public, protected or private. Public declared items can be accessed everywhere. Protected limits access to inherited and parent classes (and to the class that defines the item). Private limits visibility only to the class that defines the item.
__________________
There are No Stupid Questions. But there a LOT of Inquisitive Idiots.

Last edited by drewbee : 07-14-2008 at 05:14 PM. Reason: yes... google does work :D
Send a message via AIM to drewbee
drewbee is offline  
Reply With Quote
Old 07-15-2008, 08:14 AM   #19 (permalink)
The Prestige
Upcoming Programmer Inquisitive 
 
Tanax's Avatar
 
Join Date: Sep 2007
Location: Sweden, Stockholm
Posts: 1,080
Thanks: 115
Tanax is on a distinguished road
Default

Static methods are awesome. But not really needed in this case drewbee
__________________
Tanax is offline  
Reply With Quote
Old 07-15-2008, 06:35 PM   #20 (permalink)
The Frequenter
Newcomer 
 
xenon's Avatar
 
Join Date: Dec 2007
Location: Bucharest, Romania
Posts: 438
Thanks: 3
xenon is on a distinguished road
Default

Quote:
Originally Posted by Tanax View Post
Static methods are awesome. But not really needed in this case drewbee
That depends. If you only need only one connection to the database (you usually don't need more than one), then a singleton could be implemented:

PHP Code:
class XYZ
{
     protected static 
$instance null;
     
     public static function 
getInstance()
     {
         if(
self::$instance instanceof self === falseself::$instance = new self();

         return 
self::$instance;
     }

     private function 
__construct() { }

     private function 
__clone() { }

That way, you can't clone or create multiple instances of the same object. But again, that depends, there are cases when you need a clone of the db object (e.g.: nested fetching), and in that case it's better if you leave out the implementation of the magic clone method.
__________________
I have optimistic thoughts, even though sometimes (if not always) life's a bitch.
xenon is offline  
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 05:48 PM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design