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
Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Golbez posted:

I believe it's, the other 25,000 lines of code on the site are all procedural, so why start splitting it up into two camps?

Just because some code uses objects, it doesn't mean that it's object-oriented, or that it's not procedural in style. Are they refusing to use objects whatsoever, or just refusing to allow portions of the codebase to be written in completely object-oriented fashion?

If they are refusing to use objects at all, maybe you could find a part of the existing codebase that would particularly benefit (i.e. be made a lot simpler and more maintainable) from being refactored to use objects, and make the case for doing that. Or if you can make the case for a new piece of code being written using objects, all the better, since that doesn't involve time being spent rewriting working code. You should emphasise that just because it makes use of objects, doesn't mean it's not procedural, and that objects are sometimes an appropriate tool for the job regardless of what style the code is written in.

Adbot
ADBOT LOVES YOU

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

Hammerite posted:

Just because some code uses objects, it doesn't mean that it's object-oriented, or that it's not procedural in style. Are they refusing to use objects whatsoever, or just refusing to allow portions of the codebase to be written in completely object-oriented fashion?

If they are refusing to use objects at all, maybe you could find a part of the existing codebase that would particularly benefit (i.e. be made a lot simpler and more maintainable) from being refactored to use objects, and make the case for doing that. Or if you can make the case for a new piece of code being written using objects, all the better, since that doesn't involve time being spent rewriting working code. You should emphasise that just because it makes use of objects, doesn't mean it's not procedural, and that objects are sometimes an appropriate tool for the job regardless of what style the code is written in.

Refusing to allow objects at all. Seeing as how I'm still technically a contract worker and not a full-time employee, I'm not pushing the issue with the guy who's built this thing for the last four years - but once I have an actual job there, I'll find some way of pushing harder without pestering/sounding like a dick.

The best place for what you say would be the db code, which (if you pay attention to my posts, you know) uses mysql, rather than mysqli or PDO. What we have works, so long as we remember to escape everything, but ... I really don't know how to push this further without coming across as, well, pushy.

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

Golbez posted:

Refusing to allow objects at all. Seeing as how I'm still technically a contract worker and not a full-time employee, I'm not pushing the issue with the guy who's built this thing for the last four years - but once I have an actual job there, I'll find some way of pushing harder without pestering/sounding like a dick.

The best place for what you say would be the db code, which (if you pay attention to my posts, you know) uses mysql, rather than mysqli or PDO. What we have works, so long as we remember to escape everything, but ... I really don't know how to push this further without coming across as, well, pushy.

I guess just continue to drop hints, along the lines of "You know, this code would be a touch simpler if instead of x, we did..."? Give specific examples of where use of objects would provide a benefit. But there likely isn't any scope for you to change anything until you have more standing there.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Golbez posted:

Refusing to allow objects at all.
This is a dangerous, dangerous sign. The lead is very likely suffering from one or more of a handful of problems.
  1. He has a single, unified vision of where his software is going, and has no intention of allowing external input. This may be true especially if no code gets written without his explicit permission and/or direction.
  2. Worse, he doesn't have a single, unified version of where his software is going, or he has one and is unable to articulate it. This may be true especially if other coders on the project constantly have to ask for guidance or clarification.
  3. He may have first experienced excessive OO wankery, such as a Java framework that requires a dozen layers of indirection to get anything done, and believes that such dangerous levels of obsessive idiocy is what OO actually is.
  4. He may have an irrational distaste for OO PHP. This can frequently come from first learning PHP OO in the PHP4 era and not learning what changed in PHP5. A major hint that this may be the case is if everything is passed by reference, especially at call time or if references are discouraged.
  5. And finally, he may not understand OO and is thus afraid of it. This is the worst possible problem, and is frankly the most likely given that you're still using the mysql extension.
The project I now lead at work was built by someone that matched parts of this profile. You do not want to work under someone like this. It took the entire team threatening to ragequit (and one doing so) and some major pushing from management before he realized the scale of the problem. He quit. You might not be so lucky. (Then again, I'm not so lucky. I'm responsible for maintaining and now replacing this clusterfuck. Hopefully after I'm long gone, my name won't be cursed weekly as his is...)

McGlockenshire fucked around with this message at 06:52 on Sep 11, 2010

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

McGlockenshire posted:

This is a dangerous, dangerous sign. The lead is very likely suffering from one or more of a handful of problems.

*He has a single, unified vision of where his software is going, and has no intention of allowing external input. This may be true especially if no code gets written without his explicit permission and/or direction.
He does have some coding standards, and nothing goes live without him seeing it, but I don't think this is necessarily the situation.

quote:

*Worse, he doesn't have a single, unified version of where his software is going, or he has one and is unable to articulate it. This may be true especially if other coders on the project constantly have to ask for guidance or clarification.
It's been his for four years, I might be the first new one, I don't know. There's no other coders but us.

quote:

*He may have first experienced excessive OO wankery, such as a Java framework that requires a dozen layers of indirection to get anything done, and believes that such dangerous levels of obsessive idiocy is what OO actually is.
I doubt it, there's no Java used on the site at all, so if he did it it was probably on his own time or years ago.

quote:

*And finally, he may not understand OO and is thus afraid of it. This is the worst possible problem, and is frankly the most likely given that you're still using the mysql extension.
This is my guess.

quote:

The project I now lead at work was built by someone that matched parts of this profile. You do not want to work under someone like this. It took the entire team threatening to ragequit (and one doing so) and some major pushing from management before he realized the scale of the problem. He quit. You might not be so lucky. (Then again, I'm not so lucky. I'm responsible for maintaining and now replacing this clusterfuck. Hopefully after I'm long gone, my name won't be cursed weekly as his is...)
At this point, I need job security far more than I need to get my OO jollies. As I said, I'll wait a little bit into actually getting on board and then explain my concerns. I just need to figure out how to say it without making him mad. (I don't think he's the type, but everyone cracks under sufficient pestering) Me being the only other coder doesn't help my case much.

rugbert
Mar 26, 2003
yea, fuck you
ok so check this out, I built the three dimensional array:
code:
$products = array(
          "books" => array(
                              "title" => "friend of the family sex"
                              "author" => "Dave Chappel"
                              "Price" => "$4"
                             ),
          "movies" => array(
                              "title" => "2010"
                              "author" => "some rear end in a top hat"
                              "Price" => "$20"
                             ),
          "music" => array(
                              "title" => "sex my monkey"
                              "author" => "lady gaga"
                              "Price" => "$16"
                               "extras" => array("1","2","3","4","5",)
                             )
);

right now i can get the values from the 2nd dimension arrays with:
foreach($products as $product){
        echo $product["title"];
        echo $product["author"]
        echo $product["price"]
}
But what if, in that foreach, I need to also grab the poo poo in that last array (extras) under music?

rugbert fucked around with this message at 23:56 on Sep 11, 2010

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

rugbert posted:

But what if, in that foreach, i need to also grab the poo poo in that last array (extras) under music?

You can use the [code][/code] or [php][/php] BBCode tags to get nicely formatted code in your posts.

What do you mean by "grab the poo poo in ..."? You want to assign the $product['extras'] array to a variable? You could do that using

code:
foreach ($products as $product) {
    $title = $product["title"];
    $author = $product["author"];
    $price = $product["price"];
    if (array_key_exists("extras", $product)) {
        $extras = $product["extras"];
    } else {
        // assign something else to $extras here,
        // perhaps either an empty array or null
    }
}

rugbert
Mar 26, 2003
yea, fuck you

Hammerite posted:



ha sorry, I just woke up. Fixed my post

Sorry, I meant to echo those values. Want if I wanted to also display the values in "extras". Would I make another foreach?

rugbert fucked around with this message at 23:57 on Sep 11, 2010

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

rugbert posted:

ha sorry, I just woke up. Fixed my post

Sorry, I meant to echo those values. Want if I wanted to also display the values in "extras". Would I make another foreach?

How do you want to echo them? If you want them comma-separated, you could use

echo implode(', ', $product["extras"]);

rugbert
Mar 26, 2003
yea, fuck you

Hammerite posted:

How do you want to echo them? If you want them comma-separated, you could use

echo implode(', ', $product["extras"]);

I was planning on putting them into a select box actually, or into a list. so each item in the "extras" array would be in a list item or an option

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

rugbert posted:

I was planning on putting them into a select box actually, or into a list. so each item in the "extras" array would be in a list item or an option

Oh, ok. Well, in that case if you are just going to echo it out, using a foreach would work I guess. Something like the following perhaps

code:
echo '<ul>';
foreach ($extras as $item) {
    echo '<li>'.$item.'</li>';
}
echo '</ul>';

Iron Squid
Nov 23, 2005

by Ozmaugh
I'm working on a small script for a website. Its my first PHP project, and I need some advice.

I have a sign-up form that the user can enter some information. I'd like to spread this info out over several pages. Basically, the user enters a small bit of info, clicks next, and enters more info. Repeat until all info is collected.

Should I have one php script do this, or should each page have its own php script?

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Golbez posted:

It's been his for four years, I might be the first new one, I don't know. There's no other coders but us.
This also explains much. Learning to work as a team is a challenge.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

McGlockenshire posted:

This also explains much. Learning to work as a team is a challenge.

The funny thing is, I just came off being fired from my OWN baby that I was the sole developer on for five years. So it's not like I have any experience working on a team, which is probably why thus far I've been a doormat.

Masked Pumpkin
May 10, 2008

Iron Squid posted:

I'm working on a small script for a website. Its my first PHP project, and I need some advice.

I have a sign-up form that the user can enter some information. I'd like to spread this info out over several pages. Basically, the user enters a small bit of info, clicks next, and enters more info. Repeat until all info is collected.

Should I have one php script do this, or should each page have its own php script?

You could do it all in one page, and I'd say that's probably the simplest option code-maintenance wise - I'd say have the <form> action equal to './thispage.php?Page=2', and read in that $_GET value to determine what to ask the user next. The method of the form would still be POST, and you can drop all of that info into their $_SESSION, which you'll need to session_start() before you send any output to the browser.

The most obvious caveat is to sanitise ALL of the $_POST or $_GET variables you get from the client, especially before putting them into the database.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Iron Squid posted:

I'm working on a small script for a website. Its my first PHP project, and I need some advice.

I have a sign-up form that the user can enter some information. I'd like to spread this info out over several pages. Basically, the user enters a small bit of info, clicks next, and enters more info. Repeat until all info is collected.

Should I have one php script do this, or should each page have its own php script?

Unless there is some really compelling reason to do this ("it looks cool" is NOT a compelling reason), forms should not be spread out over multiple pages. There are lots of usability studies showing multiple-page forms have much lower completion rates, higher error rates, and frustrate users morethan single page forms.

Sylink
Apr 17, 2004

Anyone ever work with calling python scripts through PHP?

I want to have PHP present the front-end interface and deal with passing information and have python do grunt work in the background.

I am led to believe this is very possible but I'm not sure the right way to go about it.

This is all in a standard LAMP environment so having python is not an issue.''

I can do it with exec is there anything I should be worried about?

Sylink fucked around with this message at 17:00 on Sep 13, 2010

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Sylink posted:

Anyone ever work with calling python scripts through PHP?

I want to have PHP present the front-end interface and deal with passing information and have python do grunt work in the background.

I am led to believe this is very possible but I'm not sure the right way to go about it.

This is all in a standard LAMP environment so having python is not an issue.''

I can do it with exec is there anything I should be worried about?

You probably want to use http://php.net/manual/en/function.popen.php as it's marginally safer than exec. Also remember to escape poo poo http://us.php.net/manual/en/function.escapeshellarg.php

And you'll probably want to write a wrapper to do that stuff so you don't have to check the result for the normal Python errors every single time.

Edit: quick example
php:
<?
$pipe = popen("python something.py $escaped $opts $go $here", 'r');
echo chr(10),'<br><pre>&gt; ';
while(!feof($pipe)){
   $temp = fread($pipe, 1024);
   echo str_replace("\n", "\n&gt; ", $temp);
   $result .= $temp;
}
pclose($pipe);
echo '<br></pre>',chr(10);
   //the system can't find the script to run
if((strpos($result, 'something.py: command not found') === false) && 
   //python can't find a file
   (strpos($result, 'No such file or directory') === false) && 
   //some exception was thrown all the way out (script crashed)
   (strpos($result, 'Traceback (') === false) && 
   //just in case
   (strpos($result, 'Error:') === false) && 
   //the parameters changed on us
   (strpos($result, 'Usage:') === false))
{
   //feels good, man
}else die('BEES!');
?>
That spits out the result for debugging purposes.

Munkeymon fucked around with this message at 21:11 on Sep 13, 2010

Sylink
Apr 17, 2004

Exec seems easier and I don't intend to put any direct user commands into it.

Maybe I'm dumb but the usage of popen is hard to read for me.

McGlockenshire
Dec 16, 2005

GOLLOCKS!
If you can daemonize your python, and can install software on your machine, take a look at Gearman. There are python and PHP bindings.

It should make it trivial for your PHP code to call defined functions in python-land, without process control, without forking (well, forking PHP), etc.

McGlockenshire
Dec 16, 2005

GOLLOCKS!
Here's a throwback to the discussion about database interfaces. Maybe it should be in Coding Horrors instead.

Long story short, I'm fixing our "home-grown" database abstraction interface and am getting ready to send all of the changes upstream to the open source project (and original devs) that wrote it. It's grown from a "let's switch from mysql functions to an object, yay!" to a "hay, what's this mysqli thing guys?" to "gently caress MySQL, gimme Postgres! Oh, and sqlite too." SQLite support is done through PDO, and both PDO and PG do their own proper placeholder thing. After I got those using native placeholders instead of our manual replacement mechanism, I decided to tackle mysqli's prepared statements.

Now, I've always recommended mysqli, because it's mysqli. The I stands for "Improved", right? It's supposed to be better. And it is, in a lot of ways. But I never actually used any of the "improved" methods.

Has anyone actually used mysqli's prepared statements? Who designed this poo poo?
  • You have to -- have to -- specify the data type in the bind. That works fine when you're building each query manually, but when all I've got is a bunch of ?s, it's kind of hard to figure out which exact type each variable is going to be, outside of numbers.
  • You can't pass in an array of values. One at a time only. So, let's loop!
  • The bound variables are passed by loving reference. Holy poo poo, what was the designer smoking? Remember that need to loop over the arguments we got passed because it can't take an array? Yeah, that just broke everything.

What am I talking about? Here, let's look at this code:
php:
<?php
$foo range(1100);
$bar = array();
foreach($foo as $baz)
    $bar[] = &$baz;
print_r($bar);

Quick, what gets printed? If you answered 1 through 100, you are wrong.

PHP references are attached to the container -- the variable itself -- not the value stored in the container. Foreach, the best, fastest way to iterate over an array, reuses $baz in each loop, replacing the value at the start. We just created a list of 100 references to the very last element in $foo.

In order to do this correctly, I need to use an alternative loop structure (very easy, enough to make this a non-complaint), or I need to do a bizarre thing to work around foreach's behavior: foreach($foo as &$baz). See what changed? $baz is a reference there, indicating that I want the values in $foo passed into $baz by reference to begin with, thus making our assignment a reference of a reference. This would be a completely :psyboom: situation for someone that didn't understand the hosed nature of PHP references.

But it doesn't even matter, because the world explodes the instant I try to stick a string where an integer belongs. I guess I'll stick to our ancient placeholder replacement method, and stop recommending mysqli in favor of just advocating PDO.

Shame on you, PHP internals. Shame on you. Especially after you got reamed because internal functions never handle references safely. Hell, you even said you'd go back and fix all the internal functions that take references to fix them to stop this!

Why do you hate me, PHP?

Why can't I quit you?

McGlockenshire fucked around with this message at 06:28 on Sep 14, 2010

Cadoc
Mar 5, 2007

McGlockenshire posted:

:words:
php:
<?php
$foo range(1100);
$bar = array();
foreach($foo as $baz)
    $bar[] = &$baz;
print_r($bar);

more :words:
Your code outputs:
code:
Array ( [0] => 100 [1] => 100 [2] => 100 [3] => 100 [4] => 100 [5] => 100 ... ) 
php:
<?php
$foo range(1100);
$bar = array();
foreach($foo as $baz)
{
    $bar[] = $baz;
}
print_r($bar);
?>

Mine outputs (which is what you wanted if I am not mistaken):
code:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 ... )
What's different? I do not use the & before $baz.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Cadoc posted:

What's different? I do not use the & before $baz.

Right. That creates a reference, simulating how mysqli_stmt_bind_param creates references, demonstrating that using foreach to loop over arguments and passing them to the bind breaks things.

An alternative loop structure or creating the $baz as a reference in the foreach to begin with fixes that problem, but doesn't stop mysqli's designers from suffering from severe mental incapacitation.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
You don't have to declare anything in PHP. $i = 5, $s = 'fnord', etc.

But I've noticed I tend to declare arrays:
php:
<?
$array = array();
while (whatever) $array[] = 'shazam';
?>
and I realized I could drop the first line there; square-bracket syntax creates if it does not exist, I believe. Is there any drawback to this apart from code clarity? It suddenly occurred to me that it seemed weird to insist on declaring my arrays.

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Golbez posted:

Is there any drawback to this apart from code clarity? It suddenly occurred to me that it seemed weird to insist on declaring my arrays.

It's a good habit. Here's why:

php:
<?php
$foo = array();
if($bar) {
    while($baz frob())
        $foo[] = $baz->what()
}
foreach($foo as $argh)
    echo "Metasyntactic variables {$argh}, don't they?\n"
Without the initial declaration of $foo as an empty array, if the condition never fires, your foreach will try to iterate over null. That causes a warning.

Tad Naff
Jul 8, 2004

I told you you'd be sorry buying an emoticon, but no, you were hung over. Well look at you now. It's not catching on at all!
:backtowork:

Golbez posted:

You don't have to declare anything in PHP. $i = 5, $s = 'fnord', etc.

But I've noticed I tend to declare arrays:
php:
<?
$array = array();
while (whatever) $array[] = 'shazam';
?>
and I realized I could drop the first line there; square-bracket syntax creates if it does not exist, I believe. Is there any drawback to this apart from code clarity? It suddenly occurred to me that it seemed weird to insist on declaring my arrays.

I dunno; I do the same thing. I often find myself doing things like this though:
php:
<?
$a=array();
do_something_that_may_or_may_not_push_values_on($a);
foreach($a as $key=>$value){
  frob($value);
}
?>
... in which case it's nice to not have the foreach fail when $a isn't an array.

edit. beaten.

DaTroof
Nov 16, 2000

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

Golbez posted:

You don't have to declare anything in PHP. $i = 5, $s = 'fnord', etc.

But I've noticed I tend to declare arrays:

[snip]

and I realized I could drop the first line there; square-bracket syntax creates if it does not exist, I believe. Is there any drawback to this apart from code clarity? It suddenly occurred to me that it seemed weird to insist on declaring my arrays.

With strict errors enabled, referencing an undefined variable triggers a notice. Also, as McGlockenshire demonstrated, it can cause unexpected problems elsewhere and make your code harder to debug. You can get away with it, but it's not best practice.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine

DaTroof posted:

With strict errors enabled, referencing an undefined variable triggers a notice. Also, as McGlockenshire demonstrated, it can cause unexpected problems elsewhere and make your code harder to debug. You can get away with it, but it's not best practice.

Referencing, yes. Setting to, no. If I did "echo $foo[1]" before declaring $foo, that'd throw a notice. But doing "$foo[1] = 'bar'" won't throw an error, even if $foo hasn't been declared. So far as I know.

DaTroof
Nov 16, 2000

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

Golbez posted:

Referencing, yes. Setting to, no. If I did "echo $foo[1]" before declaring $foo, that'd throw a notice. But doing "$foo[1] = 'bar'" won't throw an error, even if $foo hasn't been declared. So far as I know.

Yeah, you're right. Setting $foo[] or even $foo[1] will quietly declare $foo as an array. But that doesn't change the case where $foo is unset because the loop that would have populated it never iterated.

Golbez
Oct 9, 2002

1 2 3!
If you want to take a shot at me get in line, line
1 2 3!
Baby, I've had all my shots and I'm fine
Random question time again, just a thought that popped into my head. The PHP manual says, "Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself."

Doesn't that mean that one could include a function call inside the foreach call? The manual says it works only on arrays, but couldn't a function that returns an array count?

So if I did foreach(functionthatreturnsarray() => $foo) ... ?

Fake edit: Holy poo poo, it works?
php:
<?
function foo()
{
    return array(stuff goes here);
}

foreach(foo() AS $bar)
{
    echo $bar;
}
?>
works! I've never seen this construction anywhere else. Think there's a reason for that?

McGlockenshire
Dec 16, 2005

GOLLOCKS!

quote:

I've never seen this construction anywhere else. Think there's a reason for that?

Yup. Versions prior to 5.4 (aka the current trunk) don't have the ability to dereference an array returned from a function without assigning the array to a variable first. Once you get in that habit, it's easy to forget that you can still provide functions that provide arrays to other functions and language constructs that want arrays.

Between this and traits, I'm really looking forward to 5.4.

Iron Squid
Nov 23, 2005

by Ozmaugh

Lumpy posted:

Unless there is some really compelling reason to do this ("it looks cool" is NOT a compelling reason), forms should not be spread out over multiple pages. There are lots of usability studies showing multiple-page forms have much lower completion rates, higher error rates, and frustrate users morethan single page forms.

Actually, I was thinking about this today: How long should a form be before it gets split up into multiple pages. After doing my form, it was no more than twenty questions so I'm probably going to leave it all as one page.

On a vaguely related not, HOW DO I USE GLOBAL VARIABLES IN PHP? Specifically, I want to keep a bunch of variables in an include file. Lets call it variables.php. Inside this I have something like:
code:
$html_title = "Title of My Web Page";
Then in my index.php file, I want to do something like:
code:
include 'variables.php';
echo "<title>$html_title</title>";
This doesn't work for me. I know there's some issues with the way PHP handles global files, but I'm too tired from work to figure it out.

Iron Squid fucked around with this message at 01:37 on Sep 17, 2010

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Iron Squid posted:

Actually, I was thinking about this today: How long should a form be before it gets split up into multiple pages. After doing my form, it was no more than twenty questions so I'm probably going to leave it all as one page.

On a vaguely related not, HOW DO I USE GLOBAL VARIABLES IN PHP? Specifically, I want to keep a bunch of variables in an include file. Lets call it variables.php. Inside this I have something like:
code:
$html_title = "Title of My Web Page";
Then in my index.php file, I want to do something like:
code:
echo "<title>$title</title>";
This doesn't work for me. I know there's some issues with the way PHP handles global files, but I'm too tired from work to figure it out.

That should work fine, assuming you use the same variable name. In your example here you mix using $html_title and $title. Also make sure you are including variables.php in index.php.

Iron Squid
Nov 23, 2005

by Ozmaugh

fletcher posted:

That should work fine, assuming you use the same variable name. In your example here you mix using $html_title and $title. Also make sure you are including variables.php in index.php.

Whoops. I was typing that from memory. Fixed now.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Iron Squid posted:

Whoops. I was typing that from memory. Fixed now.

It should work just fine exactly like you have it.

code:
[fletch@x ~]$ cat variables.php
<?php

        $html_title = "Title of My Web Page";

?>
[fletch@x ~]$ cat index.php
<?php

        include 'variables.php';
        echo "<title>$html_title</title>";
?>
[fletch@x ~]$ php index.php
<title>Title of My Web Page</title>

Iron Squid
Nov 23, 2005

by Ozmaugh
Err, actually I wrote my code incorrectly. The code looks more like this:
code:
$html_title = "Title of Webpage";

function printTitle(){
     echo "Welcome to $html_title";
}
When I call printTitle(), only the text "Welcome to " gets printed, not the text attached to $html_title. I think this is because PHP handles functions and global variables in an odd way, but I'm not sure how to rectify it.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Iron Squid posted:

Err, actually I wrote my code incorrectly. The code looks more like this:
code:
$html_title = "Title of Webpage";

function printTitle(){
     echo "Welcome to $html_title";
}
When I call printTitle(), only the text "Welcome to " gets printed, not the text attached to $html_title. I think this is because PHP handles functions and global variables in an odd way, but I'm not sure how to rectify it.

You need to import it from the global scope into the function's scope using the global keyword:
php:
<?
global $html_title;
?>
before you use it.

You can also use the magical $GLOBALS array:
php:
<?
$GLOBALS['html_title'];
?>
Also you can stuff arbitrary crap into the global scope from inside a function that way.

Maniaman
Mar 3, 2006
Declare that $html_title is global inside the function.

php:
<?
$html_title = "Title of Webpage";

function printTitle(){
     global $html_title;
     echo "Welcome to $html_title";
}
?>
...efb

For content:

Is it a horribly bad idea to use short tags? I've been writing an inhouse app that makes heavy use of <?=$foo;?> as opposed to <?php echo $foo; ?>. I'm not super concerned with portability (its an in-house app) but more concerned with them removing the short tags in a later version.

Maniaman fucked around with this message at 04:18 on Sep 17, 2010

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

Iron Squid posted:

Err, actually I wrote my code incorrectly. The code looks more like this:
code:
$html_title = "Title of Webpage";

function printTitle(){
     echo "Welcome to $html_title";
}
When I call printTitle(), only the text "Welcome to " gets printed, not the text attached to $html_title. I think this is because PHP handles functions and global variables in an odd way, but I'm not sure how to rectify it.

PHP: Variable scope should tell you everything you need to know. The first block of code on that page is basically what I did. The second block of code on that page is what you are trying to do. The third block of code has your answer.

Hopefully this code isn't exactly what you are trying to do, just an example, but just in case...What's the point of having a function like that though? The purpose of a function is for code that you want to reuse in other places. Having to declare $html_title outside of the function makes it pretty much useless other places, you would just have to remember what variables you have to declare before you call a function. Something like this makes more sense:

code:
//somefile.php
function printTitle($title) {
    echo "Welcome to ".$title;
}
code:
//someotherfile.php
include 'somefile.php';
printTitle("Page Title");
Also check out define, it may be more suited to what you are trying to do. Personally, I've never ever used the global keyword.

Adbot
ADBOT LOVES YOU

McGlockenshire
Dec 16, 2005

GOLLOCKS!

Maniaman posted:

Is it a horribly bad idea to use short tags? I've been writing an inhouse app that makes heavy use of <?=$foo;?> as opposed to <?php echo $foo; ?>. I'm not super concerned with portability (its an in-house app) but more concerned with them removing the short tags in a later version.

Short tags are in no danger of deprecation. ASP tags are far more likely to find themselves on the chopping block, but are safe for now.

Even then, a simple global search/replace will fix things right up. "<?=" is just a shortcut for "<?php echo"

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