B
B
billybons20062015-03-20 16:23:00
PHP
billybons2006, 2015-03-20 16:23:00

How to use method to set variable value in php script?

There is a class:

class Comment
{	
  public $name = "Name";
  
  public function getName() {
    return $this->name;
  }
  
  public function setName($var) {
    $this->name = sanitize($var);
  }

public function sanitize($str) {
    $str = trim($str);
    $str = nl2br($str);
    return $str;
  }

If, after creating the class, you set the value of the $name variable directly:
$comment = new Comment();
$comment->name = "Bla bla bla";
then everything is ok.
If I try to use the method:
$comment->setName('bla bla bla');
nothing comes out.
I can, of course, score and move on, but to be honest, I want to understand why this can be.
Can you suggest?
Added:
If the method is simplified, then everything is OK:
public function setName($var) {
    $this->name = $var;
  }

That's how it works. I don't understand why it doesn't work with the sanitize function?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
O
olamedia., 2015-03-20
@w999d

$this->sanitize();
the method belongs to the class, and not separately lying around

T
Timofey, 2015-03-20
@mr_T

In general, it is better to do this through __set, __get, so that there are no ugly entries like $obj -> set/getName, but simply access name as if it were a field of an object. Well, sanitize needs to be called as static::sanitize. Just add static to the sanitize method. Oh, and you definitely need to make PRIVATE $name, otherwise the meaning of encapsulation is lost.

B
billybons2006, 2015-03-20
@billybons2006

Thank you very much! private, of course, I'll remove it. I put it in public, because for three hours I've been trying to figure out what it is!!!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question