4

I'm trying to create a variable background, where the image changes based on the time of day. This code I have USED to work, but I did something somewhere along the line and didn't notice that the functionality had broken. Can someone explain to me why this doesn't work?

<html>
<?php

    function day()
    {
        if ( $hour >= 6 && $hour <= 18 )
        {
        return 1;
        } else { return 0; }
    }

?>

<style type="text/css">

body
{

    background-image: url('<?php echo (day() ? 'images/day_sheep.jpg'
                                             : 'images/night_sheep.jpg'); ?>');
    background-position: 50% 50%;
    background-repeat: no-repeat;
    background-color: silver
}

a {text-decoration:none;}
a:link {color:#ff0000;}
a:visited {color:#0000FF;}
a:hover {text-decoration:underline;}

</style>

</html>
2
  • 4
    Why do you use <style> outside of <head> ? Also, a nicer solution would be to define day/night class of <body>, and not change the css code. Commented Aug 26, 2010 at 13:08
  • Please show the finished CSS code in cases like this. Commented Aug 26, 2010 at 13:08

2 Answers 2

12

Inside your function day(), $hour is unset. It will be treated as 0 in a numerical context, and if you enable reporting of notices, you will see notices warning you of an unset variable. Did it used to be a global variable? Did you remove code that set its value or declared it as global?

Edit: Also, on a point of style, I feel it would look neater to have an external CSS file like this:

body {
    background-position: 50% 50%;
    background-repeat: no-repeat;
    background-color: silver
}

body.day {
    background-image: url('images/day_sheep.jpg');
}

body.night {
    background-image: url('images/night_sheep.jpg');
}

and then you can get rid of the CSS section of your php script, but include the above CSS file, and you need only have the following:

<body class="<?php echo day() ? 'day' : 'night'; ?>">
Sign up to request clarification or add additional context in comments.

1 Comment

Wonderfully helpful, thank you. It turns out I only had to add the line global $hour; to the function, but I agree that your method for defining the CSS is much more readable.
1

You never declare what $hour is.

<html>
<?php
    function day()
    {
        $hour = date('G');
        if ( $hour >= 6 && $hour <= 18 )
        {
        return 1;
        } else { return 0; }
    }

?>
... snip ...

1 Comment

$hour needs to be declared inside the function declaration, or included as a global in there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.