Assigning dynamic values to object properties in P

2020-05-05 08:03发布

问题:

I've used procedural for sometime now and trying to get a better understanding of OOP in Php. Starting at square 1 and I have a quick question ot get this to gel. Many of the basic examples show static values, e.g., $bob->name = "Robert"; when assigning a value. But I want to pass dynamic values, say from a form: $name = $_POST['name'];

class Person { 

    // define properties 
    public $name; 
    public $weight; 
    public $age;

    public function title() { 
        echo $this->name . " has submitted a request "; 
    }
} 

$bob = new Person; 

// want to plug the value in here
$bob->name = $name; 
$bob->title();

I guess I'm getting a little hung up in some areas as far as accessing variables from within the class, encapsulation & "rules", etc., can $name = $_POST['name']; reside anywhere outside of the class or am I missing an important point?

Thanks

回答1:

$bob->name = $_POST['name'];

Set the object's ($bob) name property to $_POST['name']



回答2:

$bob->name = $_POST['name'];. A safe practice in OOP is to use setter/getter methods.



回答3:

The only restriction is that you must not use an expression for defining the default value of a class member variable. For example, this is invalid syntax:

class FooBad {
    protected $bar = $_GET['bar'];
    protected $baz = 1 + 1;
}

But this is valid:

class FooGood {
    protected $bar = '';
    protected $baz = 1;
    protected $bat = array(
        1,
        2,
    );
}


回答4:

you wrote $name = $_POST['name'];, then you're assigning that value to a instance public variable (name in bob, which is instance of class Person), using the right syntax. Outside the class, $name is not the "name" inside the class of course, but again you wrote correct code, so I don't see what you think you are missing. Maybe, the fact that $name = $_POST['name']; must appear somewhere outside the class and its methods, and then you can also write

$bob->name = $_POST['name'];

of course. If you write $name = $_POST['name'] inside a class method, you are assigning to a local variable: as you already know (it can be seen in your code) you access name of the instance with $this->name. The following code hopefully clarify something

$name = "hello\n";

class Person
{
  public $name;
  public function title()
  {
    echo $this->name;
  }
  public function setit()
  {
    echo $name; // raises a Notice: undefined variable
    global $name; // now $name refers to global $name
    $name = "I am lost\n";
  }
  public function doit($n)
  {
    $this->name = $n;
  }
}

$bob = new Person;
$bob->title();      // _nothing_
$bob->name = $name;
$bob->title();      // hello
$bob->setit();      // Notice: ---
echo $name;         // I am lost
$bob->title();      // hello
$bob->doit("test\n");
$bob->title();      // test


标签: php oop