solucion index php oop

index - Clase de PHP Child que accede al problema de la variable principal



undefined index php post (5)

¿Por qué el constructor de nombre de usuario es privado? Si pretende imposibilitar la creación de un nombre de usuario, haga que la clase de nombre de usuario sea abstracta. Además, NO hagas una nueva información de contacto de la clase para padres. Aquí hay otra manera de decirlo:

abstract class Username { protected $id; protected $username; public __construct($id) { $this->id = (int) $id; // Forces it to be a string } } class ContactInformation extends Username { protected $mobile; protected $email; protected $nextel_id; public __construct($id, $mobile, $email, $nextel_id) { parent::__construct($id) $this->mobile = $mobile; .... } }

Ahora, en lugar de crear una instancia del Nombre de usuario directamente (que ahora es imposible), en su lugar crea una ContactInformation. ContactInformation llama al constructor del nombre de usuario en su propio constructor.

Tengo esta clase:

Class Username { protected $id; protected $username; protected $contact_information; private __construct($id) { $this->id = (int) $id; // Forces it to be a string $contact_information = new ContactInformation($this->id); } } Class ContactInformation extends Username { protected $mobile; protected $email; protected $nextel_id; ..... }

Mi problema es: quiero acceder a $ id y $ username (y muchas otras variables) en ContactInformation, pero parent :: o $ this-> NO funciona, parece que cada vez que lo hago "new ContactInformation ....) PHP crea un "nuevo nombre de usuario". ¿Alguna posibilidad de acceder a los valores ACTUALES desde el nombre de usuario?

Gracias


El método parent :: solo se usa para acceder a los métodos principales que ha anulado en su subclase, o variables estáticas como:

class Base { protected static $me; public function __construct () { self::$me = ''the base''; } public function who() { echo self::$me; } } class Child extends Base { protected static $me; public function __construct () { parent::__construct(); self::$me = ''the child extends ''.parent::$me; } // until PHP 5.3, will need to redeclare this public function who() { echo self::$me; } } $objA = new Base; $objA->who(); // "the base" $objB = new Child; $objB->who(); // "the child extends the base"

Probablemente quieras una subclase adecuada. No cree una subclase en el constructor de la clase base, que convierta todo tipo de prácticas recomendadas de POO al revés (acoplamiento flojo, etc.) al mismo tiempo que crea un ciclo infinito. (new ContactInformation () llama al constructor de nombre de usuario que crea una nueva ContactInformation () que ...).

Si quieres una subclase, algo como esto:

/** * Stores basic user information */ class User { protected $id; protected $username; // You could make this protected if you only wanted // the subclasses to be instantiated public function __construct ( $id ) { $this->id = (int)$id; // cast to INT, not string // probably find the username, right? } } /** * Access to a user''s contact information */ class ContactInformation extends User { protected $mobile; protected $email; protected $nextel; // We''re overriding the constructor... public function __construct ( $id ) { // ... so we need to call the parent''s // constructor. parent::__construct($id); // fetch the additional contact information } }

O podría usar un delegado, pero los métodos ContactInformation no tendrían acceso directo a las propiedades del nombre de usuario.

class Username { protected $id; protected $contact_information; public function __construct($id) { $this->id = (int)$id; $this->contact_information = new ContactInformation($this->id); } } class ContactInformation // no inheritance here! { protected $user_id; protected $mobile; public function __construct($id) { $this->user_id = (int)$id; // and so on } }


En primer lugar, cuando crea una ContactInformation , también contiene todas las propiedades y métodos no privados de Username de Username . No necesita una instancia separada de nombre de Username .

Class Username { protected $id; protected $username; protected __construct($id) { $this->id = (int) $id; // Forces it to be a string } } Class ContactInformation extends Username { protected $mobile; protected $email; protected $nextel_id; // Pretend that these are here because they''re defined in my parent //protected $id; //protected $username; public __construct($id) { parent::__construct($id); echo $this->id; //Should echo 1 } }

Sin embargo, dado que todos los campos están protegidos, esto no va a funcionar:

$contact_information = new ContactInformation(1); // Works fine echo $contact_information->id; // Whoops, visibility error because id isn''t public


Si lo entiendo correctamente, ¿desea acceder a las propiedades de un objeto desde un objeto contenido en ese objeto? Si esto es correcto, así es como se hace:

class A { // These are the properties you want to access from the child object public $property_a; public $property_b; public $property_c; // This is the child object variable public $child_object; public function __construct( ) { // Pass ''this'' into the child so that the child has a reference back to the parent $this->child_object = new B($this); } } class B { // Holds a reference to the parent object protected $parent_object; public function __construct( $object ) { // Remember the reference to the parent object $this->parent_object = $object; } // Just a Demonstration Method public print_parent_property_a() { // Reach into the referred parent object, and get it''s property print $this->parent_object->property_a; } }

Entonces, si hicieras:

$my_object = new A(); $my_object->property_a = ''test_value''; $my_object->child_object->print_parent_property_a();

Tendrás ''test_value''

Es ligeramente diferente de su ejemplo, ya que necesitará que las propiedades de la clase padre sean públicas para que el niño pueda acceder a ellas.

Todo esto funciona porque en PHP, los objetos siempre se pasan por referencia a menos que explícitamente los clones.


<?php abstract class employee { //create member variable in parent class protected $name; protected $id; protected $mobile; //constructor of parent class public function __construct($n , $i , $m) { $this->name=$n; $this->id=$i; $this->mobile=$m; } //create method will return name public function ShowFullName() { return $this->name; } //create method will return contact public function ShowContact() { return $this->mobile; } } class FulltimeEmployee extends employee { private $days; private $salary; //create child constructor public function __construct($n , $i , $mo , $d , $s) { $this->days=$d; $this->salary=$s; //calling parent constructor now we can use parent class member while calling child class constructor parent::__construct($n , $i , $mo); } public function calculate() { return $this->salary * $this->days; } } //providing data to child class constructor including parent class values $child = new FulltimeEmployee("james",120,9033474118 , 2 , 200); echo $child->calculate(); echo $child->ShowFullName();