0

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.

4
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by pritaeas
0
$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.

2

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.

1

@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.

Edited by pritaeas: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.