Page 1 of 1

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

Posted: Mon May 19, 2008 4:07 pm
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.

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

Posted: Mon May 19, 2008 4:32 pm
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;
}
?>
 

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

Posted: Mon May 19, 2008 7:35 pm
by wvxvw
Thank you. The problem solved =)