Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Tap
Apr 12, 2003

Note to self: Do not shove foreign objects in mouth.

Standish posted:

It has no set meaning, but it's often used to denote an class member or an internal function i.e. anything that shouldn't be directly used except by the original author of the code.

That's what I was looking for. Thanks!

Adbot
ADBOT LOVES YOU

SmirkingJack
Nov 27, 2002

Tap posted:

I've recently taken up PHP as my language of choice for learning how to program.

I now have a simple question regarding naming conventions in PHP.

When a variable or function is declared with a single underscore as the first character (i.e. $_foo or $_fake_function()), what exactly does this tell me as a programmer?

It's a kludge of sorts. Until PHP5 there was no way to make a variable or method private, meaning inaccessible to other objects/functions/etc so people would prepend the name with an underscore to tell other people not to use it directly. It won't stop them from doing so, but it suggests the user should do otherwise.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
When I am validating fields submitted from a form I end up with a big if/else like:

php:
<?
if (!aValid) {
    //error information
} else {
    if (!bValid) {
        //error information
    } else {
        if (!cValid) {
            //error information
        } else {
            //db interaction
        }
    }
}?>
There's gotta be a better way than that. What's the right way to do this? Should the fields be validated by the setters of my class?

fletcher fucked around with this message at 19:27 on Mar 27, 2008

functional
Feb 12, 2008

fletcher posted:

When I am validating fields submitted from a form I end up with a big if/else like:
php:
<?
IF-TREE
?>
There's gotta be a better way than that. What's the right way to do this? Should the fields be validated by the setters of my class?

Whatever you do don't use an if-tree. Can you iterate through an array of testcases/functions and then break? Try using a break or a GOTO of some sort.

functional
Feb 12, 2008

fletcher posted:

php:
<?
if (!aValid) {
    //error information
} else {
    if (!bValid) {
        //error information
    } else {
        if (!cValid) {
            //error information
        } else {
            //db interaction
        }
    }
}?>

php:
<?
$a=array(aValid,bValid,cValid);
$b=array("a error","b error","c error");
function test($a,$b)
{
 for($i=0;$i<count($a);$i++)if(!$a[$i])return $b[$i];
 return "all clear!";
}
?>

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

functional posted:

php:
<?
$a=array(aValid,bValid,cValid);
$b=array("a error","b error","c error");
function test($a,$b)
{
 for($i=0;$i<count($a);$i++)if(!$a[$i])return $b[$i];
 return "all clear!";
}
?>

How do I put my test cases in the array? Let's say I'm doing a ctype_digit() on aValid and making sure it's < someValue. Or do I do that before and just stuff the result in the array?

fletcher fucked around with this message at 19:51 on Mar 27, 2008

Standish
May 21, 2001

fletcher posted:

When I am validating fields submitted from a form I end up with a big if/else like:

php:
<?
if (!aValid) {
    //error information
} else {
    if (!bValid) {
        //error information
    } else {
        if (!cValid) {
            //error information
        } else {
            //db interaction
        }
    }
}?>
There's gotta be a better way than that. What's the right way to do this? Should the fields be validated by the setters of my class?
Use "else if" rather than nested "if"s:
php:
<?
if (!aValid) {
    //error information
} 
else if (!bValid) {
    //error information
} 
else if (!cValid) {
    //error information
} 
else {
    //db interaction    
}?>

functional
Feb 12, 2008

fletcher posted:

How do I put my test cases in the array? Let's say I'm doing a ctype_digit() on aValid and making sure it's < someValue. Or do I do that before and just stuff the result in the array?

If your tests are not time intensive, why not simply run all of them and then check at the end to see if one failed? This is what I usually do. Actually, I keep a stack of error messages and then check to see if it's non-empty.

php:
<?
$err=$array();
if(!$aValid) $err[]="a failed";
if(!$bValid) $err[]="b failed";
if(!$cValid) $err[]="c failed";

if(count($err)) echo "errors";
else echo "we're good";


?>
Alternatively, you can mimic a goto in PHP using this method: http://andy.wordpress.com/2007/06/20/dreaming-of-goto-in-php/

There are some function pointer things you can do, but to be honest it already looks like your situation is too complex for them, and it's a hassle in PHP anyway.

Congratulations, you're smarter than your programming language.

functional fucked around with this message at 20:13 on Mar 27, 2008

bt_escm
Jan 10, 2001

functional posted:

If your tests are not time intensive, why not simply run all of them and then check at the end to see if one failed? This is what I usually do. Actually, I keep a stack of error messages and then check to see if it's non-empty.

php:
<?
$err=$array();
if(!$aValid) $err[]="a failed";
if(!$bValid) $err[]="b failed";
if(!$cValid) $err[]="c failed";

if(count($err)) echo "errors";
else echo "we're good";


?>
Alternatively, you can mimic a goto in PHP using this method: http://andy.wordpress.com/2007/06/20/dreaming-of-goto-in-php/

There are some function pointer things you can do, but to be honest it already looks like your situation is too complex for them, and it's a hassle in PHP anyway.

Congratulations, you're smarter than your programming language.

Another way to do this is to iterate over the post array in a loop and use a switch statement like this
php:
<?

$errors = array();
foreach($_POST as $key=>$value){

switch($key){


   case 'email':
     //fancy email validation code
   break;

   case 'ssn':
     //fancy ssn validator
   break;

   default:
     if(empty($value)){
       $errors[$key]=$key.' cannot be empty'; 
     }
   break;
}

}

if(empty($errors)){
   //process post

} else{

  //handle errors

}
?>

functional
Feb 12, 2008

(I would prefer a string solution to this, or something built into the PHP library, and not some big package I have to install.)

I have a string which consists of potentially bad XML.

I have a tag <mytag> which may exist in the XML multiple times.

I want to return the text contained in first instance of <mytag>, or the empty string if it doesn't exist. So in the following instance:

php:
<?
<html>
<mytag>THIS_IS_THE_STRING</mytag>
<span>aaaaaa</span>
<html>
?>
I want to yank out the string "THIS_IS_THE_STRING"

Is there something that already does this or do I have to write it myself?

bt_escm
Jan 10, 2001

functional posted:

(I would prefer a string solution to this, or something built into the PHP library, and not some big package I have to install.)

I have a string which consists of potentially bad XML.

I have a tag <mytag> which may exist in the XML multiple times.

I want to return the text contained in first instance of <mytag>, or the empty string if it doesn't exist. So in the following instance:

php:
<?
<html>
<mytag>THIS_IS_THE_STRING</mytag>
<span>aaaaaa</span>
<html>
?>
I want to yank out the string "THIS_IS_THE_STRING"

Is there something that already does this or do I have to write it myself?

http://us.php.net/simplexml

functional
Feb 12, 2008


Thank you

functional fucked around with this message at 21:32 on Mar 27, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Thanks for all the replies guys, very helpful and appreciated.

Another question, is it a bad idea to use an existing php function name as the name of a method in a class? Like if I want to use $obj->delete(), wasn't sure if that's frowned upon.

MononcQc
May 29, 2007

fletcher posted:

Thanks for all the replies guys, very helpful and appreciated.

Another question, is it a bad idea to use an existing php function name as the name of a method in a class? Like if I want to use $obj->delete(), wasn't sure if that's frowned upon.
Well, if it's anything that can be confusing to someone else looking over your code, I'd say it's not a good idea. In this case, it's 99% sure to spark some confusion, so I'd go against it just because of that.

DaTroof
Nov 16, 2000

CC LIMERICK CONTEST GRAND CHAMPION
There once was a poster named Troof
Who was getting quite long in the toof

MononcQc posted:

Well, if it's anything that can be confusing to someone else looking over your code, I'd say it's not a good idea. In this case, it's 99% sure to spark some confusion, so I'd go against it just because of that.

I disagree. One of the benefits of using classes is the ability to use simple, descriptive member names that won't collide with the same name in other contexts. If $obj->delete() is an appropriate name for what the function does, I'd use it. The fact that it's obviously an object member instead of a global function should eliminate any confusion.

admiraldennis
Jul 22, 2003

I am the stone that builder refused
I am the visual
The inspiration
That made lady sing the blues

DaTroof posted:

I disagree. One of the benefits of using classes is the ability to use simple, descriptive member names that won't collide with the same name in other contexts. If $obj->delete() is an appropriate name for what the function does, I'd use it. The fact that it's obviously an object member instead of a global function should eliminate any confusion.

I agree, though delete() isn't even a built-in function...

minato
Jun 7, 2004

cutty cain't hang, say 7-up.
Taco Defender

admiraldennis posted:

I agree, though delete() isn't even a built-in function...
Yes it is: http://jp2.php.net/manual/en/function.delete.php

I tend to shy away from reusing built-in functions because it makes the syntax highlighting in my editor look odd. All built-in functions are highlighted in blue, and all others are in grey, so it looks kinda strange to see one of my functions in blue.

This usually isn't a problem as I use a camelCase naming convention, so overlap is very rare.

admiraldennis
Jul 22, 2003

I am the stone that builder refused
I am the visual
The inspiration
That made lady sing the blues

Good job reading the page you linked

quote:

This is a dummy manual entry to satisfy those people who are looking for unlink() or unset() in the wrong place.

Novicane
Oct 25, 2003

functional posted:

(I would prefer a string solution to this, or something built into the PHP library, and not some big package I have to install.)

I have a string which consists of potentially bad XML.

I have a tag <mytag> which may exist in the XML multiple times.

I want to return the text contained in first instance of <mytag>, or the empty string if it doesn't exist. So in the following instance:

php:
<?
<html>
<mytag>THIS_IS_THE_STRING</mytag>
<span>aaaaaa</span>
<html>
?>
I want to yank out the string "THIS_IS_THE_STRING"

Is there something that already does this or do I have to write it myself?


From the looks of it, you are parsing HTML which in a lot of cases can be malformed. A great extension for helping with that though is Tidy as it can cleanup and repair broken elements.

SimpleXML is a nice interface but you also have the option of using the DOM interface for interacting with XML/HTML which can sometimes give a little more flexibility. I find myself using XPath a lot for pulling content out of HTML.

tef
May 30, 2004

-> some l-system crap ->
As bad as it may sound, if you are only trying to extract text with a certain pattern, it might be easier to use a regular expression rather than a xml parser.

I.e /<mytag>([^<]*)<\\/mytag>/

tef fucked around with this message at 13:24 on Apr 1, 2008

hey mom its 420
May 12, 2007

Don't you mean /<mytag>([^<]*)</mytag>/

MononcQc
May 29, 2007

DaTroof posted:

I disagree. One of the benefits of using classes is the ability to use simple, descriptive member names that won't collide with the same name in other contexts. If $obj->delete() is an appropriate name for what the function does, I'd use it. The fact that it's obviously an object member instead of a global function should eliminate any confusion.

I just hate it when the syntax highlight goes crazy on it and highlights it as a built-in function, which then confuses me. I can tend to be distracted, so I make what's necessary to reduce my mistakes and make it easier to read for me :shobon:

other people
Jun 27, 2004
Associate Christ

Bonus posted:

Don't you mean /<mytag>([^<]*)</mytag>/

Should you not escape the forward slash in the closing tag?

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Kaluza-Klein posted:

Should you not escape the forward slash in the closing tag?

Yes, you should. However the forums like to eat escaping slashes.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
What's the point of declaring public variables in a class? If I remove them all, my application will behave the same, correct?

php:
<?
class User {
    public $id;
    public $username;
}
?>

StickBoy
Jan 28, 2006
I was wondering if there was a way to use phpmail to send an email, to be recognized by outlook calendar.

I have an event that someone would sign up for, and I want to send the email to the user, that states they have signed up for this event. But I want outlook or other mail client to be able to add it to the users calendar.

Inquisitus
Aug 4, 2006

I have a large barge with a radio antenna on it.

fletcher posted:

What's the point of declaring public variables in a class? If I remove them all, my application will behave the same, correct?

php:
<?
class User {
    public $id;
    public $username;
}
?>

Not quite sure what you mean by that.

Basically public fields are accessible from any code:

php:
<?
class Foo
{
    public $baz;
}

class Bar
{
    private $baz;
}

$foo = new Foo;
$bar = new Bar;

$foo->baz = 'baz'; // No problem here.
$bar->baz = 'baz'; // Fatal error!
?>
Edit: Unless you mean what's the point in the public modifier itself… It's just there for consistency and so that you can be explicit about it. If you want a member to be public, then declare it as such.

Inquisitus fucked around with this message at 19:57 on Mar 28, 2008

bt_escm
Jan 10, 2001

fletcher posted:

What's the point of declaring public variables in a class? If I remove them all, my application will behave the same, correct?

php:
<?
class User {
    public $id;
    public $username;
}
?>

With the way php currently handles objects there's no difference. However removing public or even not declaring the variables is just plain bad practice and could possibly break in future versions of php.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


bt_escm posted:

With the way php currently handles objects there's no difference. However removing public or even not declaring the variables is just plain bad practice and could possibly break in future versions of php.

Correct. In PHP5, if a scope isn't declared it's assumed to be public because there was no scope in PHP4.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

bt_escm posted:

With the way php currently handles objects there's no difference. However removing public or even not declaring the variables is just plain bad practice and could possibly break in future versions of php.

What's a good way to maintain my public variable declarations if they are all the exact same as my field names in the database, or do I have to just do it manually?

bt_escm
Jan 10, 2001

fletcher posted:

What's a good way to maintain my public variable declarations if they are all the exact same as my field names in the database, or do I have to just do it manually?

The simplest way is to do it manually. Alternative you could use an ORM package.
What I done in the past is build an array of the column definitions like this
php:
<?
$props = array(

'username'=>array(
   'type'=>'varchar',
   'length'=>40,
   'required'=>1),
'email'=>array(
   'type'=>'varchar',
   'length'=>255,
   'required'=>0,
   'validator'=>'email'
)

);
?>
That way I've got the full definition and validation all in one place. Then whenever creating or changing anything I can just pass the new values in and they will be full validated based on any criteria I need.

Another thing I've done in the past is use a script that I call one time to generate the above listed array after I've designed my database. It saves a little time.

bt_escm fucked around with this message at 21:09 on Mar 28, 2008

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

bt_escm posted:


What I done in the past is build an array of the column definitions like this

Wow I like that way. That makes validating all the input so much easier, thanks!

Finite
Jan 9, 2003

What do you mean mullets aren't fashionable?!?
I'm writing some authentication code for something I'm mucking around with, while at the same time trying to improve my coding habits. With the example below, CheckPassword() throws an exception if the password is incorrect.

For readabilities sake, should CheckPassword() have a boolean return and form an if block around the rest of the code, even though it won't change anything?

php:
<?
public function SetPassword($oldPassword, $newPassword, $newPassword2)
{
    if ($newPassword != $newPassword2)
    {
        throw new PasswordMismatchException();
    }

    $this->CheckPassword($this->name, $oldPassword);

    // Better?
    // if ($this->CheckPassword($this->name, $oldPassword))
    // {
            
    $salt = self::CreateSalt();
    $password = self::CreateSaltedHash($newPassword, $salt);
            
    $sql = 'UPDATE        user
        SET            password = "' . DB::Escape($password) . '"
                    salt = "' . DB::Escape($salt) . '"
        WHERE        name = "' . DB::Escape($this->name) . '"';
                    
    return $this->db->Execute($sql);

    // }
    // return false;
}
?>

Finite fucked around with this message at 11:04 on Mar 29, 2008

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Finite posted:

:words:

It looks like you're using a database abstraction layer. Use its built in prepared query functions instead of string concatenations.
It also looks like you're using PEAR::DB, any chance you can upgrade to MDB2?

bt_escm
Jan 10, 2001

Finite posted:

I'm writing some authentication code for something I'm mucking around with, while at the same time trying to improve my coding habits. With the example below, CheckPassword() throws an exception if the password is incorrect.

For readabilities sake, should CheckPassword() have a boolean return and form an if block around the rest of the code, even though it won't change anything?

php:
<?
public function SetPassword($oldPassword, $newPassword, $newPassword2)
{
    if ($newPassword != $newPassword2)
    {
        throw new PasswordMismatchException();
    }

    CheckPassword($this->name, $oldPassword);

    // Better?
    // if (CheckPassword($this->name, $oldPassword))
    // {
            
    $salt = CreateSalt();
    $password = CreateSaltedHash($newPassword, $salt);
            
    $sql = 'UPDATE        user
        SET            password = "' . DB::Escape($password) . '"
                    salt = "' . DB::Escape($salt) . '"
        WHERE        name = "' . DB::Escape($this->name) . '"';
                    
    return $this->db->Execute($sql);

    // }
    // return false;
}
?>

What you want to use is a try/catch around the the code after the newPassword to newPassword2 check.

Also your example seems really strange since you are mixing oop and procedural function calls.

Finite
Jan 9, 2003

What do you mean mullets aren't fashionable?!?

duz posted:

It looks like you're using a database abstraction layer. Use its built in prepared query functions instead of string concatenations.
It also looks like you're using PEAR::DB, any chance you can upgrade to MDB2?

It's not, it's just a database object I wrote which does some of the tedious work for me. I know that I need to look at it, but it works fine at the moment and I hadn't planned on looking at it again just yet as I'm already working on a few other things.

bt_escm posted:

What you want to use is a try/catch around the the code after the newPassword to newPassword2 check.

Also your example seems really strange since you are mixing oop and procedural function calls.

Ok. The OOP/Procedural crap is fixed. That'll teach me to post before testing for obvious errors...

I didn't want to bother using a try/catch as it's not really necessary. I want the exception to be thrown as it comes out as an InvalidPasswordException, which I think speaks for itself. My problem was whether the code was readable in it's current state, or if the call to CheckPassword() is confusing as it has no obvious way to fail.

Then again, I'm not sure if that's the best way to do this either, and it should just return true/false and I can work from there. It's more object design than PHP :)

Finite fucked around with this message at 11:06 on Mar 29, 2008

bt_escm
Jan 10, 2001
I still think a try catch would be better here because it could tell you why it failed, but after reading over your example some more the if statement would be fine.

I think this would work a lot better for you for logging purposes
php:
<?
try{

$this->CheckPassword($this->name, $oldPassword);

            
    $salt = self::CreateSalt();
    $password = self::CreateSaltedHash($newPassword, $salt);
            
    $sql = 'UPDATE        user
        SET            password = "' . DB::Escape($password) . '"
                    salt = "' . DB::Escape($salt) . '"
        WHERE        name = "' . DB::Escape($this->name) . '"';
                    
    return $this->db->Execute($sql);

} catch(SPECIFIC EXCEPTION $e) {


} catch(Exception $e){


}
?>

Treytor
Feb 8, 2003

Enjoy, uh... refreshing time!
I have since upgrade to PHP 5 and it seems my method of querying a server via a predefined URL no longer works:
code:
copy($url, '/dev/null');
How should this be done, now?

bt_escm
Jan 10, 2001

Treytor posted:

I have since upgrade to PHP 5 and it seems my method of querying a server via a predefined URL no longer works:
code:
copy($url, '/dev/null');
How should this be done, now?

check you fopen wrapper settings. also
http://us3.php.net/manual/en/function.stream-context-create.php

Adbot
ADBOT LOVES YOU

Treytor
Feb 8, 2003

Enjoy, uh... refreshing time!
Yeah, to be honest I wasn't even using fopen before. Thanks!

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply