Jump to content

Archived

This topic is now archived and is closed to further replies.

onlyican

About Classes

Recommended Posts

Hey

I am tryna learn this, and quickly

am I right in saying that if I declare a var at the top of a class, I can create a new value of in it

Also

How do I show a var
I am using php 5 on my localhost
I done this simple code

[code]
<?php
class Test
{
var $myname = "jamie";

function ShowName(){
echo $this->myname;
}
}


Test::ShowName();
?>
[/code]

And I get the followering error


Fatal error: Using $this when not in object context in W:\www\inc\class_upload_img.php on line 174

174 being the line
echo $this->myname;


Any suggestions

Share this post


Link to post
Share on other sites
[code]
<?php
  class Test {
      var $myname = "jamie";
 
      function ShowName() {
        echo $this->myname;
      }
  }

  $blah = new Test;
  $blah->ShowName();
?>
[/code]

Share this post


Link to post
Share on other sites
To use your class, you need to make a new instance of it as shown by Crayon Violent code. You can them access your method or variables using the -> operator.

Share this post


Link to post
Share on other sites
With "ClassName::methodName" you access the method statically. As the method is not declared as "static" this kind of access fails.

You may read the respective (is that the right expression?) entry in the PHP manual:
--> http://www.php.net/manual/en/language.oop5.static.php
--> http://www.php.net/manual/en/language.oop5.basic.php

Hope to help,
Regards, Ben.

Share this post


Link to post
Share on other sites
It's not the (lack of) declaration of static that is the actual cause of the error, it is the use of the pseudo variable $this that is the real failing :)

$this is a reference variable to the instantiated object of itself, so without instantiation, there is no object - thus there is no $this :)


btw, you are using PHP5.. you should make full use of the PHP5 OO syntax, namely declarations. They are the sex.

Share this post


Link to post
Share on other sites
[quote author=Crayon Violent link=topic=107350.msg430558#msg430558 date=1157723511]
[code]
<?php
  class Test {
      var $myname = "jamie";
 
      function ShowName() {
        echo $this->myname;
      }
  }

  $blah = new Test;
  $blah->ShowName();
?>
[/code]
[/quote]

That one done the trick

Thanks

My serve is still V4, they should be updating tomorrow. Till then I am playing it safe.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.