hello, i was wondering if someone can explain me what the difference is between the following classes.

I found class B nicer to use, but i want to have your comments.....

class A 
{
  public function setField($var)
  {
    $this->anyfield = $var;
  }
}
//this is how i use it
$A = new A();
$A->setField($_POST['values']);

class B 
{
  public static function setField($var)
  {
    self::$anyfield = $var;
  }
}

//this is how i use it
B::setField($_POST['values']);

Question:
- What does "static" means when declaring a function?
- Is "$this->" equal to "self: : $ " ? is there any difference?


The reason i am asking the questions is because i am about to re-code a big application I developed with PHP 4; and i want to do it right. I am also using PDO and trying to use/learn MVC.

Thank you all in advance.

Member Avatar for diafol
$this->anyfield = $var;

anyfield is not set originally - so why say it is? It has no scope - well it should have a specific scope.

IT depends on what you're trying to achieve. Both 'methods' have their place, but it depends what you want to do with them.

If your goal is refactoring an application to object oriented PHP it will save you a lot of time reading more about OO. In the specific question read more at,
www.php.net/manual/en/language.oop5.static.php
To make your example complete you should had properties (-private $ anyfield- in A and -private static $anyfield- in B )
As you can read there, static methods are callable without an instance of the object created. In your example, B is not an instance of an object, that means that you can’t have two different B’s having different $anyfield (even if you instantiate new B() ).On other hand you can have as many A’s instances you like having different $anyfield.

If a method of a class isn’t behaviour of the object then is static. For someone who doesn’t have object oriented programming experience, I believe that is best, to avoid static properties and methods, and after a while understand when should be used.

@jkon: well said. I found this note somewhere which I really like: "We use static class when there is no data or behavior in the class that depends on object identity." Personally, I try to avoid static classes. The only exception is usually a factory class.

Additionally, read up on this page. If you want to use getters/setters, than the magic functions _get() and _set() are quite useful.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.