Code Share - Page 3
Page 3 of 8 FirstFirst 12345 ... LastLast
Results 31 to 45 of 109

Thread: Code Share

  1. #31
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Running Gear"
    Posts
    22,573
    I wrote this function for Ten Green Bottles. Not the most useful of functions, but it is another use of preg_replace()'s /e modifier. I found it amusing, anyway. I'm good at amusing myself. The important bit (for a suitable value of "important") is the analysis.

    It assumes that it is being passed a string of the form [1-9][0-9]* - that is, decimal numeric representation of a positive integer.

    What it does is decrements that positive integer, returning a string representing the result in the same way.

    At first glance, one might wonder why I don't just go $n--. PHP would cast the string to an integer, and decrement it. If I used $n in a string context, it would be cast appropriately. Fine so far, but what if the string was '193275689789678975892566'? PHP wouldn't cast that to an integer because that number is too big to fit into an integer; it would be cast into a double instead. When that happens (a) decrementing is nowhere near as accurate, and (b) casting it back into a string sees characters like 'e' and '+' creeping in. For my purposes when writing this function, I wanted (a) accuracy, and (b) strictly decimal numerals.
    PHP Code:
    function l1($n)
    {
    /*1*/    if(!$n{strlen($n)-1})
    /*2*/        $n preg_replace('/(0+)$/e''strtr("$1","0","_")'$n);
    /*3*/    $n preg_replace"/(\d)(_*)$/e"'($1-1)."$2"'$n);
    /*4*/    $n strtr($n'_''9');
    /*5*/    if(!$n{0})
    /*6*/        $n substr($n,1);
    /*7*/    if($n=='') return '0';
    /*8*/    return $n;

    Before you ask, no, it doesn't check for things like leading zeros, or zero values, or negative integers. It would be easy enough to accommodate those, but it was unnecessary for me at the time. Exercise for the reader.

    Line-by line:
    1. This is a test for the sake of efficiency: it succeeds if the last digit of $n is a zero. It's not necessary, but if the last digit of $n is not a zero, then the second line will be a somewhat expensive no-op.
    2. This line matches all the trailing zeros of $n, and replaces them with underscores. '12300' becomes '123__', '1010011000' becomes '1010011___', and '42' becomes '42'. There are other ways of writing this line with a regexp - preg_replace('/0(?=0*$)/', '_', $n), for example - and it may be interesting to see which of them is quickest.
    3. This takes the last digit in the string and decrements it: '2' becomes '1', '6' becomes '5', and '9' becomes '8'. Again, this could be done differently. Oh, I do like the /e modifier. I probably use it way too often....
    4. This line is obvious: replace all underscores with '9's. If you read '_' as "negative one", you can think of lines 3 and 4 as each '_' borrowing from the digit to its left to become '9'. Then again, each '_' is '_' because it was borrowed from by the digit to its right (except the last digit which had be summarily decremented, that being the whole point of this function); accountants might like to see line 3 as recording debits, and line 4 as recording credits.
    5. If the original numeral was '1000', we'd now have '0999'. That's not quite right, so we check the first digit, and if it's a zero...
    6. ...decapitate it.
    7. Oh, what started out as '1' has now become ''. We return '0' instead of that empty string.
    8. Exercise for the reader.



    [Edit: Ten Years Later... the /e modifier is deprecated as of PHP 5.5 in favour of preg_replace_callback - like eval(), it's way too powerful and dangerous and evil to be allowed out (it's all too easy to inject arbitrary code that will be evaluated).]
    Last edited by Weedpacket; 05-02-2013 at 11:27 PM. Reason: Outdated code.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  2. #32
    Titles are overrated. Jeb.'s Avatar
    Join Date
    Jul 2003
    Posts
    150
    That function Weedpacket reminded me of this library:

    The BCMath Functions

    Highly accurate mathematical functions. Uses numbers in the forms of strings, and so avoids the double-casting, exponetial-ing, etc of PHP and C.

    Beauty of it is, they're bundled by default since PHP 4.0.4. Still, you do need to specify them at configure-time...except on Windows.
    Last edited by Jeb.; 09-28-2003 at 09:02 AM.
    Once you eliminate the impossible, whatever remains, however improbable, must be the truth. - Sir Arthur Conan Doyle

  3. #33
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Running Gear"
    Posts
    22,573

    Counting the bits in an integer.

    Yep; you could go $count=substr_count(decbin($n),'1');, but that may be a bit heavy-handed, especially if it's something you're going to be it doing a lot for some reason.

    So here are a few lines of bit-twiddling that will achieve the desired purpose. It assumes 32-bit integers:
    PHP Code:
    $n = ($n&0x55555555) + (($n >> 1)&0x55555555);
    $n = ($n&0x33333333) + (($n >> 2)&0x33333333);
    $n = ($n&0x0f0f0f0f) + (($n >> 4)&0x0f0f0f0f);
    $n = ($n&0x00ff00ff) + (($n >> 8)&0x00ff00ff);
    $n = ($n&0x0000ffff) + (($n >>16)&0x0000ffff); 
    The first line replaces each successive pair of bits with the sum of those two bits (0+0=00, 0+1=01, 1+0=01, and 1+1=10, so the space occupied by those two bits is large enough to store the result: the addition can be done in-place); the second line takes each successive pair of these sums and adds them together - again, in place (the sum is never greater than 4, which can easily fit into four bits). The process repeats twice more. Each time, the sum of each pair of sums is small enough to fit in the space previously occupied by the pair (adding two n-bit numbers requires no more than n+1 bits of space to store the result and we have 2n bits available).

    Let's got a little bit further - 'cos I'm in a didactic mood.

    The above assumes that PHP has been built for a 32-bit platform. But there are 64-bit machines out there as well, and the above code will fail to count half the bits in a 64-bit integer. Now, while the sort of situations where you want to count bits are the sort where you know you're only going to be interested in the first 32 or so, a look at seeing how to support both architectures in one script in this instance might give ideas about how to cope with other situations.

    First of all, we need to know how that code will look when written for a 64-bit machine. I leave that as an exercise for the reader (basically, the constants are twice as long, and there is a sixth line). Now that we have that, we need to be able to switch back and forth between them.

    Now, we don't want to have to go around cutting-and-pasting blocks of code like that whenever we want to move between 32-bit and 64-bit machines. But we don't need to. We can set a constant and have it do the work of switching as appropriate:
    PHP Code:
    define('INT64'true);
    if(
    INT64)
    { include_once 
    '64bitfunctions.php');
    }
    else
    { include_once 
    '32bitfunctions.php');

    But we'd still need to swap the value of INT64 back and forth between true and false ourselves.

    No we don't. PHP can determine at compile/runtime whether it is running on a 64-bit or 32-bit machine and set the value of the constant accordingly. All we need is a bit of code that can be evaluated at that time that will tell us what we want to know.

    It is a property of the two's-complement arithmetic notation which is pretty much universally used to represent binary integers that -1 is represented by a string of 1 bits. Ideally an infinitely long string, but on real computers they're generally restricted to the size of one CPU word - 32 bits on a 32-bit machine, 64 bits on a 64-bit machine.

    So what we want to do is find out how many 1 bits our current machine uses to represent -1, and use that to determine whether INT64 should be true or false. Let's do that, then.

    PHP Code:
    define('INT64'strlen(decbin(-1))==64);
    if(
    INT64)
    { include_once 
    '64bitfunctions.php');
    }
    else
    { include_once 
    '32bitfunctions.php');

    Yes, I know, I used decbin() after all. But instead of using it every time I want to count the number of bits in an integer (which would more likely than not be inside a loop), I only use it once, to determine how many bits I'll be needing to look at.

    Edit: and now that the PHP_INT_SIZE constant exists, that last decbin() call can go after all because we can just check the value of that. But are there that many 32-bit platforms still being used?
    Last edited by Weedpacket; 12-08-2017 at 08:27 PM.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  4. #34
    Better fan than rebelo! Moonglobe's Avatar
    Join Date
    Apr 2003
    Location
    brain://localhost:left-side
    Posts
    2,044
    //Moonglobe's jaw drops.........

    OMG Weed, that's some really interesting code! whoa....... if i understood the bitwise operators maybe i could apreciate it even more!
    there's no place i can be, since i found serenity.

  5. #35
    black sheep with red wool Merve's Avatar
    Join Date
    Jul 2003
    Location
    North of the 49th parallel
    Posts
    2,193
    Nice code, Weed. (Too bad I'm too thickheaded to understand it )
    "A proof is a proof. What kind of a proof? It's a proof. A proof is a proof. And when you have a good proof, it's because it's proven." -- Jean Chrétien

    The Three C's

  6. #36
    Computers can do that? drawmack's Avatar
    Join Date
    Apr 2003
    Location
    Pocono Mtns PA
    Posts
    3,265
    Weed, that's really cool and unless the function is implemented that way in c++ then I would gues you'd be at least an order of magnitude faster.

  7. #37
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Running Gear"
    Posts
    22,573

    Mutant Schwartzian Transforms Save the World

    A couple of threads recently in the Coding Help Forum revolved around sorting an array according to a fairly complex criterion. One was to sort book titles alphabetically, ignoring HTML tags and boring words like "the" and "and"; the other was to sort email addresses by domain.

    Now the most straightforward approach is probably to write a comparison function that compares two elements of the array, and determines which of the two (if either) is "larger" according to the criterion; then using that function as a callback in usort, and given the conditions, probably the best answer to be going on with in those threads.

    It got me thinking, though (something has to, I suppose): it can be a bit expensive. Sometimes this may be unavoidable without a lot more hassle, but in others (and the two examples above are cases in point), some savings can be made.

    The reason for the saving is this: when comparing two book titles (say), one can take the two elements being compared, and transform both of them into some canonical form (stripping HTML tags, boring words and punctuation - and I know it's a slight abuse of the word "canonical"), and generally simplifying both titles until they're easy to compare. But the comparison function is likely to be called many times, and the same value may be passed to it as either the first or second argument many times - the conversion to canonical form is going to be carried out every time. That makes for a lot of duplicated effort.

    It would be a lot nicer in this case to just do the canonicalisation once per argument, and then do all the comparsions.

    In Perl circles this was recognised quite a while ago, and Perl Guru Randall Schwartz came up with a Perl idiom known as the Schwartzian Transform. What follows here is a rough PHP analogue (or maybe "metaphor" would be closer to the mark) of that idiom.

    So. We have a list of items in an array which I'll call $original_array. From it we create a new array $sorted_array that uses the values of $original_array as keys, and has the corresponding canonical forms as their values.

    Say we want to sort email addresses by domain, do it from the top down, and we don't really care about the exact order of name parts.
    PHP Code:
    function canonicalise_emails($address)
    {    list(
    $localpart$domain) = explode('@'$address);
        
    $domain strtolower($domain);
        
    $subdomains explode('.'$domain);
        
    $subdomains array_reverse($subdomains);
        
    $domain join('.'$subdomains);
        return 
    $domain;

    Recall that if the above were a usort() callback, it would take two addresses, do the same exploding, reversing and joining on both of them, and then compare the resulting domains, returning the result of the comparison as a number <, =, or > 0.

    As described, we'd use the above function like this:
    PHP Code:
    $sorted_array = array();
    foreach(
    $original_array as $address)
    {    
    $sorted_array[$address] = canonicalise_emails($address);

    Now we are in a position to sort. We want to sort $sorted_array according to its values, maintaining key association
    PHP Code:
    asort($sorted_array); 
    Now, we don't want to keep the canonicalised form, but the original form. Those are the keys of $sorted_array:
    PHP Code:
    $final_array array_keys($sorted_array); 
    And we're done!

    Ah, but we're not! (No, we never are, are we?) Two or three problems arise.

    First of all, what if the elements of $original_array aren't necessarily unique? If there are duplicates we can't use them as array keys without losing the duplicates. What if the elements of the array aren't strings? That will also make things go wonky.

    Both of these problems are solved by making the process even more similar to the Schwartzian Transform. In that, the array $sorting_array becomes an ordinary (indexed) array in which each element consists of two elements. The zeroth is the canonical form, the first is the original form. Then the sorting is done based on the value of the zeroth elements.
    PHP Code:
    function canonicalise_emails($address)
    {    
    // derive $domain as above
        
    return array($domain,$address);

    The actual sorting is the same regardless of the canonicalisation process, so we might as well make it a function
    PHP Code:
    function canonical_email_comparison($a,$b)
    {    return 
    strcmp($a[0],$b[0]);

    which we can use as a callback in a usort() call (hey, did I ever say "Don't Use usort()" (except just there)? I did not. I've said "usort() is your friend. Take it home. Get it drunk..." and that's quite the opposite.

    PHP Code:
    usort($sorted_array,'canonical_email_comparison'); 
    After that we just go through and retain the first el$address:
    PHP Code:
    $final_array=array();
    foreach(
    $sorted_array as $address)
    {    
    $final_array[]=$address[1];

    (For those who like callback functions, these things can be lifted to even higher levels of abstraction....)

    The third problem alluded to is when a canonical form isn't easy to derive: perhaps there are several things about the two terms being compared that need to be checked, one after the other, some are easy and dealt with quickly, some are harder and take more effort, and so forth. In such a situation, where it is difficult (or impossible) to find a way to canonicalise each term independently of the others, the above method is not so useful. But in situations where it can be done with little more (or even less) effort than a usort() comparison function, the mutant Schwartzian transform can very well be the timesaver in PHP that the real Schwartzian transform is in Perl.

    (Please, Mr/Ms/Mrs Mod; can those really long lines of code be shortened?)
    Last edited by Weedpacket; 12-08-2017 at 08:28 PM.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  8. #38
    black sheep with red wool Merve's Avatar
    Join Date
    Jul 2003
    Location
    North of the 49th parallel
    Posts
    2,193
    but you are a mod

    Nice code weed!
    "A proof is a proof. What kind of a proof? It's a proof. A proof is a proof. And when you have a good proof, it's because it's proven." -- Jean Chrétien

    The Three C's

  9. #39
    WARNING: I am watching u! jayant's Avatar
    Join Date
    Aug 2002
    Location
    New Delhi, India
    Posts
    886
    Originally posted by Merve
    but you are a mod
    Not in EL.
    Here Ms. Larty rules
    Jayant Kumar Gandhi
    Computer Help | GZip/ Page Compression Test | My pic/ How I look?
    Marking the thread as 'resolved' is more important than saying "thanks. that solved it"
    Click "Mark Thread Resolved" in the thread tools and the top of the thread.
    Keep sensible thread titles.

  10. #40
    Senior Member
    Join Date
    Mar 2002
    Location
    Nottingham UK.
    Posts
    372
    A nice newbie pagination script...

    Just define how many results per page you want, your query and your mysql login credentials and away you go

    PHP Code:
    <?php

    // Pagination Script

    // Define number of results per page
    $limit 10;

    // Insert Query Here (leave out any LIMIT commands)
    $query "SELECT * FROM posts";

    // Log into MySQL database
    $db mysql_connect("localhost""dbusername""dbpassword") or die ("Could not connect"); 
    mysql_select_db("dbname") or die ("Could not select db");

    // If $page is not defined, then default it to page 1
    if(empty($page)) {
    $page 1;
    }

    // query database to find total number of records to display 
    $get_total_rows mysql_query($query$db) or die ("Error Executing Query"); 
    $total_rows mysql_num_rows($get_total_rows);

    $limitvalue $page $limit - ($limit);

    $result mysql_query("$query LIMIT $limitvalue$limit"$db) or die ("Error Executing Query");  
    $count_result mysql_num_rows($result);

    // Various Calculations
    $numofpages ceil($total_rows $limit); 
    echo 
    "$total_rows Results Found (" $numofpages " Pages)<br><br>"
    $from=$limit*$page-$limit+1
    $to=$from $count_result-1

    // Display Current Result Location
    if($numofpages 1) {
    echo 
    "Showing Results: $from - $to<br><br>";


    // Echo results
    while ($data mysql_fetch_array($result)){

    // Echo results here in this format:

    echo "$data[db_column_name1]<br>";
    echo 
    "$data[db_column_name2]<br>";
    echo 
    "$data[db_column_name3]<br>";

    }

    echo 
    "<br>";

    // display previous link if page is not 1 
    if($page != 1){  
    $pageprev $page 1;
    echo 
    "<a href=\"$PHP_SELF?page=$pageprev\"><< Back</a> ";
    }  

    // Start Numbers
    for($i$page-4$i $page+5$i++) {

    if(
    $i $numofpages) {
    break;
    }

    if(
    $i 1) {
    continue;
    }

    if (
    $page == $i) {
    echo 
    " [$i]";
    } else {
    echo 
    " <A HREF=\"$PHP_SELF?page=$i\">$i</A>";
    }

    }

    // display next page link if there is more than one 
    if(($total_rows-($limit*$page)) > 0){
    $pagenext $page 1
    echo 
    " <A HREF=\"$PHP_SELF?page=$pagenext\">Next >></A>";



    mysql_free_result($get_total_rows);
    mysql_free_result($result);
    mysql_close($db);

    ?>
    Last edited by jonno946; 01-29-2004 at 07:12 AM.

  11. #41
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Running Gear"
    Posts
    22,573

    Procrastination as an art form.

    Here was the method as originally written:
    PHP Code:
    function pdf($x)
    {    if(
    $x<0) return 0;
        
    $lglg = ($this->nu1*log($this->nu1)+$this->nu2*log($this->nu2))/2;
        
    $lg12 sf_lngamma(($this->nu1+$this->nu2)/2);
        
    $lg1 sf_lngamma($this->nu1/2);
        
    $lg2 sf_lngamma($this->nu2/2);
        return 
    exp($lglg+$lg12-$lg1-$lg2)*
            
    pow($x$this->nu1/2-1)*
            
    pow($this->nu2+$this->nu1*$x, -($this->nu1+$this->nu2)/2);   

    Now, the most important bits of context are:
    • sf_lngamma() is a fairly expensive function to evaluate - which we didn't want to do any more often than absolutely necessary.
    • It is also deterministic - depending only on its arguments.
    • The parameters, $nu1 and $nu2, are constant for the life of the object.


    So there is a lot of computation going on in the above method - with the vast majority of it guaranteed to produce the same result every time. But let's say I evaluated the expensive constant factor in that function (if you look, you'll notice that really there is only one spread out over several statements) and stored it in a property, initialised at instantiation?
    PHP Code:
    function __construct($r$nu1$nu2)
    {    
    $this->$r;
        
    $this->nu1 $nu1;
        
    $this->nu2 $nu2;
        
    $lglg = ($nu1*log($nu1)+$nu2*log($nu2))/2;
        
    $lg12 sf_lngamma(($nu1+$nu2)/2);
        
    $lg1 sf_lngamma($nu1/2);
        
    $lg2 sf_lngamma($nu2/2);
        
    $this->pdf_constant exp($lglg+$lg12-$lg1-$lg2);
    }

    function 
    pdf($x)
    {    if(
    $x<0) return 0;
        return 
    $this->pdf_constant*
            
    pow($x$this->nu1/2-1)*
            
    pow($this->nu2+$this->nu1*$x, -($this->nu1+$this->nu2)/2);   

    So far so good; but the problem is that the pdf() method isn't necessarily going to be called during the lifetime of the object. In such a situation, all that calculation (still quite expensive) is again wasted. It would be nice if that expensive constant could be evaluated once and only when needed. Well, we can do that. We can evaluate the constant in the pdf() method if we first check that we haven't already done so.
    PHP Code:
    function pdf($x)
    {    if(
    $x<0) return 0;
        if(!isset(
    $this->pdfconstant))
        {    
    $lglg = ($this->nu1*log($this->nu1)+$this->nu2*log($this->nu2))/2;
            
    $lg12 sf_lngamma(($this->nu1+$this->nu2)/2);
            
    $lg1 sf_lngamma($this->nu1/2);
            
    $lg2 sf_lngamma($this->nu2/2);
            
    $this->pdfconstant exp($lglg+$lg12+$lg1-$lg2);
        }
        return 
    $this->pdfconstant*
            
    pow($x$this->nu1/2-1)*
            
    pow($this->nu2+$this->nu1*$x, -($this->nu1+$this->nu2)/2);   

    Oddly enough, the sf_lngamma() function (the natural logarithm of the Γ function) is not used anywhere else in the class, and there's a good chance it's not used anywhere else in the script. Since it's a mildly long and elaborate bit of code, let's avoid loading and parsing it when it's not necessary. include_once() handles half the job, so we'll just have to deal with the "only" part. Move the inclusion from the top of the file to:
    PHP Code:
    function pdf($x)
    {    if(
    $x<0) return 0;
        if(!isset(
    $this->pdfconstant))
        {    include_once(
    'sf_gamma.php');
            
    $lglg = ($this->nu1*log($this->nu1)+$this->nu2*log($this->nu2))/2;
            
    $lg12 sf_lngamma(($this->nu1+$this->nu2)/2);
            
    $lg1 sf_lngamma($this->nu1/2);
            
    $lg2 sf_lngamma($this->nu2/2);
            
    $this->pdfconstant exp($lglg+$lg12+$lg1-$lg2);
        }
        return 
    $this->pdfconstant*
            
    pow($x$this->nu1/2-1)*
            
    pow($this->nu2+$this->nu1*$x, -($this->nu1+$this->nu2)/2);   

    Last edited by Weedpacket; 04-21-2006 at 05:49 AM. Reason: Typos and the elimination thereof
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  12. #42
    Senior Member
    Join Date
    Jun 2003
    Location
    Charlottesville
    Posts
    208
    Pythagorean Tripples:

    PHP Code:
    function PerfectSquare($dblNumber){
            
    $temp 0.0;
            
    $temp sqrt($dblNumber);

            if (
    round($temp0) == $temp) {
                return 
    true;
            } else {
                return 
    false;
            }
    }
    for(
    $a 1$a <= 100$a++){
        for(
    $b 1$b <= 100$b++){
            
    $c = ($a*$a) + ($b*$a);
            if(
    PerfectSquare($c)){
                
    $c sqrt($c);
                echo 
    $a."\t".$b."\t".$c."\n"."<br>";
            }
        }


  13. #43
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Running Gear"
    Posts
    22,573
    Originally posted by benkillin
    Pythagorean Tripples:
    Mmm... but, e.g., 1 3 2 is not a Pythagorean triple (the bug: you've got $b*$a instead of $b*$b).


    PHP Code:
    for($m=2$m<=100$m++)
    {    
    $m2 $m*$m;
        for(
    $n=1$n<$m-1$n++)
        {    
    $n2 $n*$n;
            
    $a=$m2+$n2;
            
    $b=2*$m*$n;
            
    $c=$m2-$n2;
            echo 
    $a."\t".$b."\t".$c."\n";
        }

    Where the gcd code elsewhere in this thread could be used to strip out common factors.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  14. #44
    Copyleft Commie bubblenut's Avatar
    Join Date
    Oct 2003
    Location
    London
    Posts
    2,318
    Handy little tip I've just discovered. PHP4 doesn't support static class parameters so here's a nasty, dirty hack to help. It'll make you feel like you just woke up from an unsavory dream about your grandmother (No, not happy, *dirty* ) but it'll get the job done.

    PHP Code:
    //Declare the variable in the top level 
    //It doesn't have to be initialised here but if
    //it isn't you'll want a little more checking in
    //the constructor.
    $variable=0;
    class 
    TestClass {
      var 
    $variable;

      function 
    TestClass() {
         
    //Bring the top level variable into the local space
        
    global $variable;
        
    //And then pass it by reference to the  class parameter
        
    $this->variable =& $variable;
      }

      function 
    incVar() {
        return ++
    $this->variable;
      }
    }

    //Let's see it in action
    $a=new TestClass();
    $b=new TestClass();
    echo(
    $a->incVar()." - ".$b->incVar()." - ".$a->incVar()." - ".$b->incVar()."<br />\n"); 
    HTH
    Bubble
    If at first it doesn't work, slap it with a dirty hack.

    Moral of the week: Never let a moral of the week go on for more than a week, it's even sillier than feeding the admins.

    My Blog

  15. #45
    Settled 4 red convertible dalecosp's Avatar
    Join Date
    Jul 2002
    Location
    Accelerating Windows at 9.81 m/s....
    Posts
    8,546

    An awful useful app...

    Well, I hunted and hunted for something "shareworthy", but it's just not here.

    But, I'll share anyway

    And so sorry, bubblenut and whomever else: everything I write is "dirty", although not always "quick".

    We no longer have a chore list or shopping list on the refrigerator in our house; now it's on any browser on the LAN. It's probably awful; not compliant with any standards or even good coding practice...so why are you getting to see "shopping.php"? It was the smallest, least convoluted app that looked even remotely useful. Yeah, it's horrible, too. You'll need a MySQL Database (we have one for more than just the shopping list), a web server, and 'head.php' (sample quoted):
    PHP Code:
    <?php

    session_start
    ();
    include 
    'funct.php';

    ?>
    <html>
       <head>
          <title>My Shopping List</title>
    <?php
    if ($_SESSION['alert']) {
            
    $jsalert=$_SESSION['alert'];
            unset(
    $_SESSION['alert']);
            echo 
    "
    <script language=javascript type=text/javascript>
         alert(\"
    $jsalert\")
    </script>
    "
    ;
    }
    ?>
       </head>
       <body>
          <h1>My Shopping list</h1>
    <hr>
    You'll want "foot.php", but it can be anything:
    PHP Code:
    <?php
    function foo() {
            return 
    1;
    }
    foo();
    ?>
    Finally, I'll attach "funct.php" to this post, and the actual "shopping.php" app to the next one...overkill, to be sure...
    /!!\ mysql_ is deprecated --- don't use it! Tell your hosting company you will switch if they don't upgrade! /!!!\ ereg() is deprecated --- don't use it!

    dalecosp "God doesn't play dice." --- Einstein "Perl is hardly a paragon of beautiful syntax." --- Weedpacket

    Getting Help at All --- Collected Solutions to Common Problems --- Debugging 101 --- Unanswered Posts --- OMBE: Office Machines, Business Equipment

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •