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
TreFitty
Jan 18, 2003

This question is so simple it's (near) impossible to find an answer for: I've tried several servers - each running PHP5 - and I can't figure out why echo won't work. I copy code straight from the Hello World chapter of a book and it throws a parsing error every time. Why?

code:
<?php
echo “<p>Hi!</p>”;
?>
I mean...come on. Seriously? I know 5 languages very well, but have never touched PHP in my life. I'm stumped on this. What gives?

This is code directly copied and pasted from my clipboard.

edit: the problem appears to be coming from inserting HTML tags in an echo construct. If that's the case, first of all, what the gently caress is with that? Second of all, why would it be made this way in my book?

Third, what are you supposed to do instead?

edit2: It appears that:
code:
<?php
echo("<p>whatwhatinthebutt</p>");
?>
...is what I'm supposed to do but I only arrived at that conclusion based on messing around with it a little. Should I abandon the three books that I've looked at so far that tell me to do poo poo that doesn't work?

TreFitty fucked around with this message at 11:59 on Jun 13, 2009

Adbot
ADBOT LOVES YOU

gibbed
Apr 10, 2006

What's the error? You're not giving enough information, given that there can be server settings to run other PHP code in addition to yours, etc, that would help.

Edit: Oh, it's not that at all. It's your verbatim copying of the code from the guide. The “” are not properly interpreted as " by PHP, fix that and you fix the code.

gibbed fucked around with this message at 11:59 on Jun 13, 2009

TreFitty
Jan 18, 2003

I can't believe it. I didn't even see that the quotes were all retarded. I thought that the editor I was using was doing that. Thanks, gibbed. I'm much less confused now.

Battle Bott
May 6, 2007

Question:
How do I get php to serve files like apache?

Background:
Okay, I have a directory that I store (mostly) static files in, /c/ This directory is web-accessible. I have granted people ftp access to some subdirectories in there.

I wanted to track downloads and such on those files, so I used htaccess to redirect everything from /dl/xxxxx to /whatever/index.php?file=xxxxx index.php tracks the hit, then serves the file (/c/xxxxx) using readfile.

I also wrote a file browsing system, so that going to /dl/subdirectory/ would give you a directory listing of /c/subdirectory/, which apache would do already, but mine is prettier. I also coded commenting and ratings and such that is applied though this directory listing system. This is ALL done through index.php.

While testing I realized that somebody had uploaded a copy of mediawiki into their ftp directory, and at some point I had given them a mysql database to run it. Usually no problem, because browsing to the php settings files would normally return a blank page, but my custom (and horrible) system just serves the php as flat text, which shows passwords. Bad.

Here is the way I'm doing things now, which is wrong:
code:
$mime=getmime($I['file']);
header('Content-type: $mime');
readfile($dataroot.$I['file']);
Here is a possibility, though it changes the url back to /c/, which I don't want:
code:
header("Location: ".$dataroot.$I['file']);
Before you fret, everything is properly protected against injection, ..'s, and all of that other stuff. All other content in /c/ is public, and can be viewed.
Help?

Edit:
Here is the thingy. I have only coded the logic, the html is just to make sure it works.
http://bottlabs.org/dl/

Here is the directory it is browsing (htaccess will swoop you away):
http://bottlabs.org/c/dlfiles/

Oh, and if you are clever, test comments and ratings by logging in, by setting a cookie "user=123"

There is nothing important in that directory, it is just for testing.

Battle Bott fucked around with this message at 05:11 on Jun 15, 2009

duck monster
Dec 15, 2004

Try reading the file in, making GBS threads it back out, and tacking on an appropriate mime header there.

Battle Bott
May 6, 2007

duck monster posted:

Try reading the file in, making GBS threads it back out, and tacking on an appropriate mime header there.

Which is exactly what I'm doing. I don't want to serve files, I want to *execute* them, and if they don't execute, I want to pass them on.

Also, my WAMP "Uniform Server" does not have mime_content_type. The function does not exist, is it unix only? finfo_file does not work either.

Agrikk
Oct 17, 2003

Take care with that! We have not fully ascertained its function, and the ticking is accelerating.
I need help breaking up lines of data in a flat file into variable to be imported into a database, and explode() doesn't seem to cut it.

The data that I have is in this format
code:
Depot         1511 A686354-F D Lo Ni             123 Im M4 V
Nubotech      1513 C362556-9   Ni                422 Im F4 III M8 D
Justends Four 1514 D567100-5   Lo Ni             712 Im F8 V M3 D
Ashima        1515 E443942-A   Hi In Po          810 Im G6 V
Koorfagh      1602 E67377B-5                     323 Va M1 V
Gagh Veth     1603 X556423-1   Ni              R 334 Va F2 V
Silibast Ti   1605 E350553-9   Ni Po De          413 Im M5 V F3 V
Khukish       1606 A77A989-F   Hi In Wa Cp       823 Im G9 V
Shishkala     1607 B686654-C   Ag Ni Ri          613 Im A2 V
With the following legend:

1-18: Name
20-23: HexNbr
25-33: UWP (eight sub-variables with a length of 1 each. the hyphen will be omitted)
36: Bases
38-52: Codes & Comments (up to seven sub-variables, space delimted)
54: Zone
57-59: PBG (three sub-variables with a length of one each)
61-62: Allegiance
64-80: Stellar Data (Up to six sub-variables, space delimted)

Explode() will split it up using a delimiter like " ", but what I'd like to do is specify some method where I can grab some characters out of the string of some specific length and stuff it into a variable. The length of the grabbed data varies and will potentially contain spaces in it.

How can I accomplish this?

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:

Agrikk posted:

I need help breaking up lines of data in a flat file into variable to be imported into a database, and explode() doesn't seem to cut it.
...
How can I accomplish this?

I'd suggest unpack(), which seems to be tailor made for splitting out fixed-length fields, and as a bonus you get to specify the packed type. That or a bunch of messy substr()'s...

gibbed
Apr 10, 2006

Battle Bott posted:

Which is exactly what I'm doing. I don't want to serve files, I want to *execute* them, and if they don't execute, I want to pass them on.
You want to execute arbitrary code uploaded by random people? :raise:

8ender
Sep 24, 2003

clown is watching you sleep
Heres an odd request. I'd like to find a PHP script that will let me setup a mailing list that I can then mirror into a database.

The reason for this is that I have some existing forum software that needs some work. I've added some features to have new threads emailed to users that "subscribe" to a forum but what they'd like now is to be able to reply to those notification emails and have their replies go to all the other subscribers and be posted as a reply to the topic in the forum.

I hope I'm being clear here. Its an annoying request but a half the people using this site are really old and really love their mailing lists. The other half are perfectly happy using the forum software.

The script below looked promising but its custom tailored to PHPBB. I don't know if I have the PHP skills to modify it without the result being a big dirty hack. I'm more used to developing in Java.

http://mail2forum.com/

Battle Bott
May 6, 2007

gibbed posted:

You want to execute arbitrary code uploaded by random people? :raise:

Private ftp. So yes.

KuruMonkey
Jul 23, 2004
In your htacces, where you redirect everything to /index.php?file=pqr.xyz

Don't redirect it at all if your file is pqr.php

Then your site will go back to dealing with PHP as it normally does.

Use your actual web server logs to see what the webserver has served, rather than reinventing that feature for yourself...

Battle Bott
May 6, 2007

KuruMonkey posted:

In your htacces, where you redirect everything to /index.php?file=pqr.xyz

Don't redirect it at all if your file is pqr.php

Then your site will go back to dealing with PHP as it normally does.

Use your actual web server logs to see what the webserver has served, rather than reinventing that feature for yourself...

Hmm, I guess that would work. Not very elegant.

Anyway, this whole deal is coding practice, it isn't actually important.

cannibustacap
Jul 7, 2003

Brrrruuuuuiinnssss
I have a multi-part array I need to sort..

Basically, I need to sort all the elements by "num_transactions" from greatest to lowest. But, all the PHP array

code:
    [per_keyword] => Array
        (
            [direct/bookmark] => Array
                (
                    [revenue] => 371.48
                    [num_transactions] => 11
                )

            [26 mm watch band] => Array
                (
                    [revenue] => 28.45
                    [num_transactions] => 1
                )

            [replacement watch bands] => Array
                (
                    [revenue] => 43.4
                    [num_transactions] => 1
                )

            [watch band] => Array
                (
                    [revenue] => 65.8
                    [num_transactions] => 2
                )

            [watchbands] => Array
                (
                    [revenue] => 58.85
                    [num_transactions] => 2
                )
I'm not really sure which PHP functions can do this: http://us.php.net/manual/en/array.sorting.php

Is there a PHP function or a script out there that can do this?

Hammerite
Mar 9, 2007

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

http://us.php.net/manual/en/function.array-multisort.php

Unfortunately I think you need to do something similar to example #3 on that page, which involves a bit of extra work to get the data into a format that array_multisort will work with.

cannibustacap
Jul 7, 2003

Brrrruuuuuiinnssss

Hammerite posted:

I think array_multisort is what you need.

http://us.php.net/manual/en/function.array-multisort.php

Unfortunately I think you need to do something similar to example #3 on that page, which involves a bit of extra work to get the data into a format that array_multisort will work with.

Sweet, yeah I was able to make example 3 work:

code:
foreach ($keywords[per_keyword] as $key => $val) {
	$num_trans[$key] = $val[num_transactions];
}
array_multisort($num_trans,SORT_DESC,$keywords[per_keyword]);

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

I'm storing a list of integers in a comma separated textfield on MySQL and then explodin them into an array. I then check through a list of 25 integers and see if they are on the original list. Is there a better way to do this?

php:
<?
$galaxy = "144,145,119,118,117,92,93,68,69,70,91,116";

$explored = explode(",", $galaxy);

// this is done in a loop up to 25 times
if( in_array($current, $explored) )
{
echo "blah";
}
?>

gibbed
Apr 10, 2006

drcru posted:

I'm storing a list of integers in a comma separated textfield on MySQL and then explodin them into an array. I then check through a list of 25 integers and see if they are on the original list. Is there a better way to do this?

php:
<?
$galaxy = "144,145,119,118,117,92,93,68,69,70,91,116";

$explored = explode(",", $galaxy);

// this is done in a loop up to 25 times
if( in_array($current, $explored) )
{
echo "blah";
}
?>
array_intersect.

slutcannon
Jan 18, 2005

I need a goon auth script to work with SMF. A good amount of goons have been kind enough to lend me their code; while I can read PHP well enough I don't understand CURL and am a bit too stupid to make it work for myself. Need this for Darkfall Online goons.

Here's a vbulletin version a goon kindly donated to me that I think does quite a bit more than I'd actually need but nevertheless it's a good start.


e cut

slutcannon fucked around with this message at 17:26 on Jun 19, 2009

Battle Bott
May 6, 2007

slutcannon posted:

I need a goon auth script to work with SMF. A good amount of goons have been kind enough to lend me their code; while I can read PHP well enough I don't understand CURL and am a bit too stupid to make it work for myself. Need this for Darkfall Online goons.

Here's a vbulletin version a goon kindly donated to me that I think does quite a bit more than I'd actually need but nevertheless it's a good start.

Well, what do you know about what the script is doing? Once you know what it is doing you can just modify it. You also need to know the internals of SMF's user system. To do this you'd need a good knowledge of php mysql and smf. Describe what you think this script is doing, and we can help with the hazy parts.

Battle Bott fucked around with this message at 08:59 on Jun 19, 2009

awesomepanda
Dec 26, 2005

The good life, as i concieve it, is a happy life.
Hi everyone

im using the following php code to record ip addresses

<html>

<body>

<?php
$myFile = "LogFile.txt";
$file = fopen($myFile, 'a');
$zdate = date("m:d:Y\tG:i:s");
$ip=$_SERVER['REMOTE_ADDR'];
$zdate = $zdate."\t".$ip."\n";
fwrite($file, $zdate);
fclose($file);
?>

</body>

</html>

but for some reason i get this symbol every now and then � in the record

can someone explain to me what this means and how i can correct for it?

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

You're using two different character encodings.

Zajako
Dec 11, 2002
the one the only
Hello, I'm making an import tool, that imports data from one site system to another. The original system had urls in the page text similar to:

local://index.php?action=website-view&WebSiteID=366&WebPageID=9029/
/index.php?action=website-view&WebPageID=20407&WebSiteID=366
/index.php?action=website-view&WebPageID=20407
index.php?action=website-view&WebPageID=20407
local://index.php?action=website-view-item&WebSiteID=9&ItemID=1949/
http://website.com/index.php?action=website-view-category&WebSiteID=9&CategoryID=509
http://website.com/index.php?action=website-view-catalog&WebSiteID=9
/index.php?action=website-view-item&WebSiteID=9&ItemID=1948
local://index.php?action=website-view-item&WebSiteID=9&ItemID=1948/

I need the following information from the regex:

I need the domain name if set.
I need the action if set.
I need the WebSiteID if set.
I need the WebPageID if set.
I need the ItemID if set.
I need the CategoryID if set.

I will recreate all other parts of the links, as my script actually pulls the name of these pages for the link.

I also need to be sure that nothing is left behind in the texts (misc slashes, etc). As the old editor randomly put slashes and domains, and a local:// tag, the regex needs to check if all or any of these elements are there.

For someone who actualy understands regex, this should not be too difficult, however, I only know some of the basics. I was able to make an expression that caught some of them, however, there are 475 sites I need to import, and over 25,000 pages across them. I need to ensure that this expression will catch most if not all links.

A second part to this, that is also important, is the images embeded into the page content, which should use another expression.


Some example image urls

http://www.anything.com/images-pdgo/image-18701.gif
http://anything.com/images-pdgo/image-18701.gif
/images-pdgo/image-18701.gif
images-pdgo/image-18701.gif
local://images-pdgo/image-18701.gif
/images-pdgo/image-301.jpg

The pieces I need from this set are:


I need the domain name if set.
The id number (ending part of filename).
The extension of the file.



I'm currently using these crappy ineffective expressions that I threw together that only cover some of what I'm wanting above:
code:
	$find[] = '#local://index.php\?action=(.*)\&amp\;WebSiteID=(.*)\&amp\;WebPageID=(.*)\/#esiU';
	$replace[] = "v1urltotemp('\\3')";
	$find[] = '#local://index.php\?action=(.*)\&amp\;WebPageID=(.*)\&amp\;WebSiteID=(.*)\/#esiU';
	$replace[] = "v1urltotemp('\\2')";
	$find[] = '#"/index.php\?action=(.*)&amp;WebPageID=(.*)&amp;WebSiteID=(.*)"#esiU';
	$replace[] = "v1urltotemp('\\2')";
	$find[] = '#"/index.php\?action=(.*)&amp;WebPageID=(.*)"#esiU';
	$replace[] = "v1urltotemp('\\2')";
	
	$find[] = '#[url]http://[/url](.*)/images\-pdgo/image\-(.*)"#esiU';
	$replace[] = "v1imgtov2('\\2','\"')";
	$find[] = '#\images\-pdgo/image\-(.*)"#esiU';
	$replace[] = "v1imgtov2('\\1','\"')";
	$find[] = '#images\-pdgo/image\-(.*)"#esiU';
	$replace[] = "v1imgtov2('\\1','\"')";
These just simply arnt enough, for me to start importing sites, as they only work for some sites, and don't cover all types of links.

I really need these expressions tonight, so any help is appreciated.

Internet Headache
May 14, 2007
Put away the regex. As a fake programmer, PHP offers you a pile of functions to allow you to avoid exerting any sort of mental effort (until your application reaches critical mass).

I recommend looking into parse_url() and parse_str(). Use parse_url to grab the domain and whatever path things you need, and then parse_str on the query string to grab the fields into an array and work with them regardless of their order in the original query string. With this information, you can rebuild a string rather than feeding preg_replace() a mountain of search patterns.

Internet Headache fucked around with this message at 09:09 on Jun 22, 2009

Zajako
Dec 11, 2002
the one the only

Internet Headache posted:

Put away the regex. As a fake programmer, PHP offers you a pile of functions to allow you to avoid exerting any sort of mental effort (until your application reaches critical mass).

I recommend looking into parse_url() and parse_str(). Use parse_url to grab the domain and whatever path things you need, and then parse_str on the query string to grab the fields into an array and work with them regardless of their order in the original query string. With this information, you can rebuild a string rather than feeding preg_replace() a mountain of search patterns.
The problem here is, most of these links don't have a full url. And a regex would work perfectly here.

I have the main find's figured out, however, for some reason, they are not passing the variable for the replace.

code:
$find[] = '#"[local://|/]*index.php\?action=[a-zA-Z0-9_-]*[&|&amp;]*[WebSiteID=[0-9]*]*[&|&amp;]*WebPageID=([0-9]*)[^"]*"#esiU';
	$replace[] = "v1urltotemp('\\1')";
	$find[] = '#"[local://|/]*index.php\?action=[a-zA-Z0-9_-]*[&|&amp;]*[WebSiteID=[0-9]*]*[&|&amp;]*ItemID=([0-9]*)[^"]*"#esiU';
	$replace[] = "v1urltotemp('\\1','','item')";
These are passing null for \\1 When both strings clearly have a number where the only group is.

Munkeymon
Aug 14, 2003

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



Zajako posted:

And a regex would work perfectly here.

Not unless you want to get into some extremely complex expressions.

You can split (explode) them on ? and then use a combination of simple regular expressions, parse_url, and splitting on & to get the information you want. It will end up much less of a mindfuck than trying to shoehorn this problem into one regex.

DaTroof
Nov 16, 2000

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

Zajako posted:

The problem here is, most of these links don't have a full url.

You can use parse_url() on relative paths. They have to be pretty goddamned malformed before it throws up on them.

php:
<?
$urls = array(
    'local://index.php?action=website-view&WebSiteID=366&WebPageID=9029/',
    '/index.php?action=website-view&WebPageID=20407&WebSiteID=366',
    '/index.php?action=website-view&WebPageID=20407',
    'index.php?action=website-view&WebPageID=20407',
    'local://index.php?action=website-view-item&WebSiteID=9&ItemID=1949/',
    'http://website.com/index.php?action=website-view-category&WebSiteID=9&CategoryID=509',
    'http://website.com/index.php?action=website-view-catalog&WebSiteID=9',
    '/index.php?action=website-view-item&WebSiteID=9&ItemID=1948',
    'local://index.php?action=website-view-item&WebSiteID=9&ItemID=1948/'
);
foreach ($urls as $u) {
    $parts = parse_url($u);
    if (isset($parts['query'])) {
        parse_str($parts['query'], $parts['variables']);
    }
    print_r($parts);
}
?>
Output:

code:
Array
(
    [scheme] => local
    [host] => index.php?action=website-view&WebSiteID=366&WebPageID=9029
    [path] => /
)
Array
(
    [path] => /index.php
    [query] => action=website-view&WebPageID=20407&WebSiteID=366
    [variables] => Array
        (
            [action] => website-view
            [WebPageID] => 20407
            [WebSiteID] => 366
        )

)
Array
(
    [path] => /index.php
    [query] => action=website-view&WebPageID=20407
    [variables] => Array
        (
            [action] => website-view
            [WebPageID] => 20407
        )

)
Array
(
    [path] => index.php
    [query] => action=website-view&WebPageID=20407
    [variables] => Array
        (
            [action] => website-view
            [WebPageID] => 20407
        )

)
Array
(
    [scheme] => local
    [host] => index.php?action=website-view-item&WebSiteID=9&ItemID=1949
    [path] => /
)
Array
(
    [scheme] => http
    [host] => website.com
    [path] => /index.php
    [query] => action=website-view-category&WebSiteID=9&CategoryID=509
    [variables] => Array
        (
            [action] => website-view-category
            [WebSiteID] => 9
            [CategoryID] => 509
        )

)
Array
(
    [scheme] => http
    [host] => website.com
    [path] => /index.php
    [query] => action=website-view-catalog&WebSiteID=9
    [variables] => Array
        (
            [action] => website-view-catalog
            [WebSiteID] => 9
        )

)
Array
(
    [path] => /index.php
    [query] => action=website-view-item&WebSiteID=9&ItemID=1948
    [variables] => Array
        (
            [action] => website-view-item
            [WebSiteID] => 9
            [ItemID] => 1948
        )

)
Array
(
    [scheme] => local
    [host] => index.php?action=website-view-item&WebSiteID=9&ItemID=1948
    [path] => /
)
Is there something else you need?

Edit: ah, I just noticed it doesn't like the URLs with a local scheme, but that should be trivial enough to detect.

DaTroof fucked around with this message at 17:35 on Jun 22, 2009

Jreedy88
Jun 26, 2005
thirty4
I'm trying to pass some PHP strings to JavaScript. I'm doing this for an AJAX request on the server. The problem comes when the string contains either a " or '. Is there a function I can use to put escape characters in there so that when I call the echo, it echoes the entire string and doesn't get cut off in the wrong spot?

php:
<?
$job = 1" Trim;
echo "ordernumber.innerHTML = \"$job\";\n";
?>
This breaks horribly. Help me fix it.
To be clear, I have no control over $job. It's being pulled from a SQL database where both ' and " are allowed.

EDIT: Found my fix. Unsurprisingly, the name of the function I needed was addslashes().
http://us2.php.net/addslashes

Jreedy88 fucked around with this message at 20:03 on Jun 22, 2009

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:

Jreedy88 posted:

I'm trying to pass some PHP strings to JavaScript. I'm doing this for an AJAX request on the server. The problem comes when the string contains either a " or '. Is there a function I can use to put escape characters in there so that when I call the echo, it echoes the entire string and doesn't get cut off in the wrong spot?

php:
<?
$job = 1" Trim;
echo "ordernumber.innerHTML = \"$job\";\n";
?>
This breaks horribly. Help me fix it.

To be clear, I have no control over $job. It's being pulled from a SQL database where both ' and " are allowed.

I made this thing after getting too insane with escaping HTML for exporting to JS:
php:
<?
function jsescape($str){
        $str=str_replace(
                array('"',"\n"),
                array('"+String.fromCharCode(34)+"','\\n'),
                $str);
        return '"'.$str.'"';
}
?>
Then you'd just do:
code:
echo "ordernumber.innerHTML = ".jsescape($job).";\n";

Hammerite
Mar 9, 2007

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

Jreedy88 posted:

I'm trying to pass some PHP strings to JavaScript. I'm doing this for an AJAX request on the server. The problem comes when the string contains either a " or '. Is there a function I can use to put escape characters in there so that when I call the echo, it echoes the entire string and doesn't get cut off in the wrong spot?

php:
<?
$job = 1" Trim;
echo "ordernumber.innerHTML = \"$job\";\n";
?>
This breaks horribly. Help me fix it.

To be clear, I have no control over $job. It's being pulled from a SQL database where both ' and " are allowed.

Maybe addslashes()?

I'm not sure I've understood what you're trying to do. That code you've given us isn't valid PHP.

Jreedy88
Jun 26, 2005
thirty4

Hammerite posted:

Maybe addslashes()?

I'm not sure I've understood what you're trying to do. That code you've given us isn't valid PHP.

The reason it was broken PHP was because there were quotes within the strings. I was trying to accentuate that point. addslashes() was exactly what I needed, and I have now fixed the issue.

Zajako
Dec 11, 2002
the one the only
Thanks guys, I ended up using a similar method using parse_url, however still needed a preg_replace to find the urls in the mix of the page content.

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

How come it won't let me overload this function with time()? I seem to be able to do it with array()...

php:
<?
public function get_foo_bar( $cutoff = time() )
{
//
}?>
"Parse error: syntax error, unexpected '(', expecting ')' in "

gibbed
Apr 10, 2006

drcru posted:

How come it won't let me overload this function with time()? I seem to be able to do it with array()...

php:
<?
public function get_foo_bar( $cutoff = time() )
{
//
}?>
"Parse error: syntax error, unexpected '(', expecting ')' in "
array() is a language construct, not a real function.

supster
Sep 26, 2003

I'M TOO FUCKING STUPID
TO READ A SIMPLE GRAPH
That's not overloading, that's default argument values (aka optional parameters) and they must be a constant expression (a function call is not).

Acer Pilot
Feb 17, 2007
put the 'the' in therapist

:dukedog:

Cool, thanks for the explanations.

gibbed
Apr 10, 2006

You could do something like this instead, though:
php:
<?php
    public function get_foo_bar($cutoff false)
    {
        if ($cutoff === false)
        {
            $cutoff time();
        }
    }
?>

Battle Bott
May 6, 2007

I have an arbitrary list of choices, each paired with an arbitrary (positive) value. Since this is a PHP thread, let's call it an array. I can format this data however I want, that's not an issue.
code:
"choice 1"=>2,
"choice 2"=>4
I want to randomly select one of the choices with the value influencing the decision. In this case choice 2 would be twice as likely as choice 1.

I have not yet taken stats, and I have no idea how to go about this (properly)
A horrible way would be to make a new array and add each item according to it's value, then simply select a random item:
(I simply 2/4 to 1/2 using magic)
code:
"choice 1",
"choice 2",
"choice 2"
In this case choice 2 would be twice as likely to be chosen randomly, I think.

Then you run into this:
code:
"choice 1"=>1,
"choice 2"=>1.5
Solved easily enough:
code:
"choice 1",
"choice 1",
"choice 2",
"choice 2",
"choice 2"
And then:
code:
"choice 1"=>1.129875,
"choice 2"=>3.214589
Yeah.

This is used commonly, I just can't figure out how it's done.

edit:
Found the term:
Weighted random selection.

Battle Bott fucked around with this message at 08:04 on Jun 25, 2009

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
This is more general programming theory, but what is the best way to handle data in an object? Have a generic record and functions to handle it, or make a separate function for each piece of data?

Example of the first one (the method I currently use):
php:
<?
class Record
{
  private $Record = array();

  function __construct()
  {
    //This initializes $this->Record, creating empty array entries, including 'foo' and 'bar')
  }

  public function setData($type,$data)
  {
    if (array_key_exists($type,$this->Record)) { $this->Record[$type] = $data; }
  }

  public function getData($type)
  {
    if (array_key_exists($type,$this->Record)) { return $this->Record[$type]; }
  }
}
?>
Example of the second one:

php:
<?
class Record
{
  private $foo = '';
  private $bar = '';

  public function setFoo($data)
  {
    $this->foo = $data;
  }

  public function getFoo()
  {
    return $this->foo;
  }
}
?>

Adbot
ADBOT LOVES YOU

KuruMonkey
Jul 23, 2004

Golbez posted:

This is more general programming theory, but what is the best way to handle data in an object? Have a generic record and functions to handle it, or make a separate function for each piece of data?

There's no real single answer, other than "depends on the situation".

If part or all of your class's attributes are similar, and can be served by a single get/set pair that is parameterised, then do so.

If part or all of your class's attributes require different get/set processing depending on which attribute it is, then individual functions are better than a massive switch($key) in the set function.

Sometimes the answer is a bit of both; if you have a set of attributes that can be dealt with simply en-masse and can be grouped then a single get/set pair for those and individual ones for the rest is in order. Sometimes you'll want multiple sets of get/set functions, but each is still doing the get($k)/set($k, $v) thing for different groups.

Here's a bad example:
php:
<?
class Xhtml
{
    private $tagname = '';
    
    private $attributes = array();
    
    private $classes = array();
    
    function __construct($tagname)
    {
        $this->tagname = $tagname;
    }
    
    public function create($tagname)
    {
        return new Xhtml($tagname);
    }
    
    public function setAttribute($attribute, $value)
    {
        $this->attributes[$attribute] = $value;
        return $this;
    }
    
    public function addClass($classname)
    {
        $this->classes[] = $classname;
        return $this;
    }

    public function render()
    {
        $classes = '';
        if(count($this->classes) > 0)
            $classes = 'class="'.implode(' ', $this->classes).'" ';
        
        $attributes = '';
        foreach($this->attributes as $attribute=>$value)
        {
            $attributes .= $attribute.'="'.$value.'" ';
        }
            
        return "<{$this->tagname} {$classes}{$attributes}/>";
    }
}

// useage:
echo Xhtml::create('img')
    ->setAttribute('src', 'images/happycat.jpg')
    ->setAttribute('alt', 'A Happy Cat')
    ->addClass('align_right')
    ->addClass('drop_shadow')
    ->render();

?>
Most of the attributes can be set by a single setAttribute function, but because a tag can have lots of classes, it needs a separate function to aggregate them instead of overwriting each time.

Basically you have to consider the class you are looking at at the time, and make the choice based on that class, not try to make the decision once and for all.

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