Pregunta

Not sure if this is even a question. My understanding of protected/private properties and methods is that they can only be accessed from within the class. I have a static method which is sort of a quick method for saving an object to a database. I creating the object from within the static method and setting properties through setter functions. One property however has no setter and yet, I am still able to access it. I have a class that looks something like this:

class Person {

   protected $name;
   protected $email;
   protected $created;

   //set name
   public function set_name( $name ) {
       $this->name = $name;
   }

   //set email
   public function set_email( $email ) {
       $this->email = $email;
   }

   //add new person
   static function add( $data ) {

       $person = new Person;
       $person->set_name( $data['name'] );
       $person->set_email( $data['email'] );

       //set created date
       $person->created = date('Y-m-d h:ia', time());

       //save to db
       $db->add($data);

       return $person;

   }

}

Implementation looks something like this:

$person = Person::add(array(
   'name' => 'Bob Barker',
   'email' => 'bob@thepriceisright.com'
));

This code works. By works I mean that the created date get set successfully. Why?

¿Fue útil?

Solución

Protected properties can be modified by code within the class, not just from instances of that class.

Otros consejos

Because you're setting it within the class. The setters are often used for setting the variables from outside from the class, such as Person::set_name('Bob Barker'). But if you tried Person->created = date(), it should fail.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top