[basic] Creating a class, how can I access class' variables?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
wvxvw
Forum Newbie
Posts: 22
Joined: Sat May 17, 2008 10:55 am

[basic] Creating a class, how can I access class' variables?

Post by wvxvw »

Hi, I'm new to PHP, but not to the programming in general. Here I've tried to create a really basic class and to call it's method. But seems like I'm missing something basic... (I've followed the tutorial from here: http://www.spoono.com/php/tutorials/tutorial.php?id=27) Please, can you tell me what's wrong with the code below?
Here's the code for class:

Code: Select all

<?php 
class PageBody {
    var $css = 'styles.css';
    
    var $sorce = '';
    var $div = '<div></div>';
    var $img = '<img>';
    var $pattern = '/></i';
    var $replacement = 'class="$class_name"';
    
    function PageBody () {
        //$sorce = preg_replace($pattern, $replacement, $div);
    }
    
    function to_string () {
        $output = $this->$div;
        return $output;
    }
}
?>
And here I'm trying to use it:

Code: Select all

<?php
    include('classes/page_template.php');
    $page = new PageBody();
    echo $page->to_string();
?>
TIA.
User avatar
slightlymore
Forum Newbie
Posts: 9
Joined: Sun May 18, 2008 5:24 pm
Location: Oxford, England

Re: [basic] Creating a class, how can I access class' variables?

Post by slightlymore »

in the tostring function, get rid of the $ before the div variable. The code you've written there would be interpreted as a variable variable.

http://uk.php.net/language.variables.variable

The rule is that you don't need a dollar sign after the oo arrow as I call it (->)

Code: Select all

 
<?php
function to_string () {
    $output = $this->div;
    return $output;
    // another alternative is to just return it instead of assigning it
    return $this->div;
}
?>
 
wvxvw
Forum Newbie
Posts: 22
Joined: Sat May 17, 2008 10:55 am

Re: [basic] Creating a class, how can I access class' variables?

Post by wvxvw »

Thank you. The problem solved =)
Post Reply