PHP class array object method access issue - php

I wrote a class
class User {
private $cars = array(); //store class Car 's object
public function getCars()
{
return $this->cars;
}
public function setCars($cars)
{
$this->cars = $cars;
}
}
class Car{
private $model;
public function getModel()
{
return $this->model;
}
public function setModel($model)
{
$this->model = $model;
}
}
$user = new User();
$cars = $user->getCars();
$cars[0]->getModel();
When I try to access getModel() php report "Call to undefined method stdClass::getModel()" .
Is there the best practice to deal with such case?
Edit:I filled the getter and setter. In fact, It's generated by phpstorm.
Edit:I tried again and it works well with the demo code below. The original code is too complicated to show. Maybe I caused by my misunderstanding of copying by value and by reference of array.
Please ignore this question. sorry.
class User {
private $cars = array(); //store class Car 's object
public function getCars()
{
return $this->cars;
}
public function setCars($cars)
{
$this->cars = $cars;
}
}
class Car{
private $model;
public function getModel()
{
return $this->model;
}
public function setModel($model)
{
$this->model = $model;
}
}
$user = new User();
$car = new Car();
$car->setModel("Ford");
$arr = $user->getCars();
array_push($arr,$car);
$user->setCars($arr);
foreach($user->getCars() as $car) {
var_dump($car->getModel());
}

You haven't shown your [Getter Setter ] code. You need to create one with something like:
public function setCars($val){
$this->cars = $val;
}
public function getCars(){
return $this->cars;
}
The same applies for getModel()

Related

Assigning child classes to a variable in parent class

I have these related classes:
class cars {
public $cars;
public function addCar($name, $car)
{
$this->cars[$name] = $car;
}
public function getCars()
{
return $this->cars;
}
public function getCar($name)
{
return $this->cars[$name];
}
public function getParams()
{
return $this->params;
}
}
$cars = new cars();
class bmw extends cars {
private static $_instance = null;
protected $params;
function __construct()
{
$this->params['param'] = 'foo';
}
public static function init()
{
if (self::$_instance === null) {
self::$_instance = new self;
}
return self::$_instance;
}
}
$cars->addCar( 'bmw', bmw::init() );
Basically i need to access all child classes from parent class. And use methods defined in parent class on those defined child classes. Parent class should not be modified when adding new child classes.
In the end this should work like this:
foreach( $cars->getCars() as $car )
{
foreach( $car->getParams() as $key => $param )
echo "$key = $param";
}
What is the proper way to do this?
It's really difficult to provide an help since it's not so clear what you're trying to achieve.
It seems to me that you need Registry Class (carDealer), an abstract class with common (for each child) methods and a child (Bmw) of this.
So, something like:
// You seems to need what is called sometimes a Registry.
// Something which deal with keeping and delivering a group of 'related' classes, as a register.
class CarsDealer
{
public $cars;
public function addCar($name, $car)
{
$this->cars[$name] = $car;
}
public function getCars()
{
return $this->cars;
}
public function getCar($name)
{
return $this->cars[$name];
}
}
// then you need a basic contract for each concrete classes
// that will have the same nature and so will extend it
abstract class Car
{
protected $params;
public function getParams()
{
return $this->params;
}
}
// finally the concrete class
class Bmw extends Car
{
public function __construct($params = null)
{
$this->params['param'] = $params;
}
}
$carsDealer = new CarsDealer();
$carsDealer->addCar('bmw', new Bmw('foo'));
foreach ($carsDealer->getCars() as $car)
{
foreach ($car->getParams() as $key => $param) {
echo "$key = $param";
}
}
Please pay attention to some basic rules/good practices/conventions:
class naming, always capitalized
Responsibilities (a class Bmw shouldn't have a method getCars, at least not in this example)
Visibility of method, parameters
http://www.php-fig.org/psr/psr-1/
http://www.php-fig.org/psr/psr-2/
Just one another approach, if you just need get this 'params' :-)
class cars {
public $cars;
public function addCar($name, $car)
{
$this->cars[$name] = $car;
}
public function getCars()
{
return $this->cars;
}
public function getCar($name)
{
return $this->cars[$name];
}
public function getParams($obj)
{
return $obj->params;
}
}
$cars = new cars();
class bmw extends cars {
private static $_instance = null;
protected $params;
function __construct()
{
$this->params['param'] = 'foo';
}
public static function init()
{
if (self::$_instance === null) {
self::$_instance = new self;
}
return self::$_instance;
}
}
$cars->addCar( 'bmw', bmw::init() );
print_r( $cars->getParams($cars->getCar('bmw')));

programming book example doesn't work: a car is not an object

The following code taken from a 2010 PHP book I a m currently reading returns a "Fatal error: Call to a member function getPrice() on a non-object in Z:\home\different-tasks\www\cardecorator.php on line 15" How come that a car is not an object?
<?php
abstract class AbstractCar {
public abstract function getPrice();
public abstract function getManufacturer();
};
class Car extends AbstractCar {
private $price = 16000;
private $manufacturer = 'Acme Autos';
public function getPrice() { return $this->price; }
public function getManufacturer() { return $this->manufacturer; }
};
class CarDecorator extends AbstractCar {
private $target;
function __construct( Car $target ) { $this->target = $target; }
public function getPrice() { return $target->getPrice(); }
public function getManufacturer() { return $target->getManufacturer(); }
};
class NavigationSystem extends CarDecorator {
public function getPrice() { return parent::getPrice()+1000; }
};
$car = new Car();
$car = new NavigationSystem( $car );
//$car = new LeatherSeats( $car );
echo $car->getPrice();
public function getPrice() { return $target->getPrice(); }
should be
public function getPrice() { return $this->target->getPrice(); }
you have several mistakes like this there
I went on to download the examples from the publisher's site, and the downloadsable code works. The author explicitly mentioned in the preface that some elements of the examples given in the printed version might be missing to provide conciseness.
So,I guess that I should study the code that is downloaded rather than what is printed.

PHP simple chain class methods without create object

in this below class i want to use class like with static methods and for use class methods without create new object from parent.
for example:
<?php
class Permission
{
protected $permission = false;
protected $id = 0;
public static function __construct()
{
return new static;
}
public function user( $id )
{
$this->id = $id;
}
public function check()
{
$this->permission = true;
}
public function item( $item )
{
return $item;
}
}
$bar = Permission::user(100)->item("HELLO");
print_r($bar);
this code not working and have problem. how to resolve this class problem?
That will not work because user method is not static, try changing this two methods, and this is good way of generating objects
public function __construct($id)
{
$this->id = $id;
}
public static function user( $id )
{
return new static($id);
}
I'd suggest you a singleton pattern, like this
class Permission
{
static protected $permission = false;
static protected $id = 0;
private static $_instance = null;
private function __construct () { }
public static function getInstance()
{
if (self::$_instance === null) {
self::$_instance = new self;
}
return self::$_instance;
}
public static function user( $userId )
{
self::$id = $userId;
return self::$_instance;
}
public static function check()
{
self::$permission = true;
return self::$_instance;
}
public static function item( $item )
{
return $item;
}
}
$bar = Permission::getInstance()->user(100)->item("HELLO");
print_r($bar);
You can chain methods in 'dynamic' classes by returning $this at the end of method (remember, you have a static).
class A {
public function someMethod()
{
// some code
return $this
}
public function otherMethod()
{
// some code
return $this
}
$a = new A();
$a->someMethod()->otherMethod();
}

PHP Method Chaining: Calling one method before allowing other methods to be chained

Consider the following class
class myClass {
private $model;
public function update($input) {
return $this->model->update($input);
}
public function find($id) {
$this->model = ORMfind($id);
}
}
How do I prevent
$myClass = new myClass;
$myClass->update($input);
The problem isn't HOW to use the above code but how to make update() a method only callable after find().
EDIT: I changed what my method does so it was more clearly understood that I need to do one method (find()) before another (update())
You could add a flag to your code like so:
class myClass {
private $model;
private $canUpdate = 0;
public function update($input) {
if ($canUpdate === 0) return; // or throw an exception here
return $this->model->update($input);
}
public function find($id) {
$this->model = ORMfind($id);
$canUpdate = 1;
}
}
Setting the flag $canUpdate will caution the update() method to react accordingly. If update() is called, you can throw an exception or exit out of the method if the flag is still 0.
To prevent from returning null value by get :
public function get() {
if (isset($this->value)) return $this->value;
else echo "please give me a value ";
}
You can also create a construct:
function __construct($val){
$this->value=$val;
}
and then give a value to your $value without using set() method:
$myClass=new myClass(10);
Outputting text, returning void, I think all of this is wrong. When you do not expect something to happen, you should throw an exception:
class MyClass {
private $canUpdate = false;
public function find($id) {
// some code...
$this->canUpdate = true;
}
public function canUpdate() {
return $this->canUpdate;
}
private function testCanUpdate() {
if (!$this->canUpdate()) {
throw new Exception('You cannot update');
}
}
public function update($inpjut) {
$this->testCanUpdate();
// ... some code
}
}
Now you can do:
$obj = new MyClass();
try {
$obj->update($input);
} catch (Exception $e) {
$obj->find($id);
$obj->update($input);
}
The proper way to make sure ->update() can only be called when the model has been initialized is to turn it into a dependency:
class myClass
{
private $model;
public function __construct($id)
{
$this->model = ORMfind($id);
}
public function update($input) {
return $this->model->update($input);
}
}
$x = new myClass('123');
Alternatively, if you have multiple find operations, you could introduce them as static constructor methods:
class myClass
{
private $model;
private function __construct($model)
{
$this->model = $model;
}
public function update($input) {
return $this->model->update($input);
}
public static function find($id)
{
return new self(ORMfind($id));
}
}
$x = myClass::find('123');
Update
Tackling your immediate problem can be done by a simple check:
public function update($input) {
return $this->model ? $this->model->update($input) : null;
}

PHP Observer Pattern, Issue

Bellow is a PHP script.
I tried to implement the Observer pattern (without MVC structure)... only basic.
The error which is encountered has been specified in a comment.
First I tried to add User objects to the UsersLibrary repository. There was a error such as User::update() does not exists or something.
Why is that error encountered? What fix should be applied and how?
interface IObserver {
public function update(IObservable $sender);
}
interface IObservable {
public function addObserver(IObserver $obj);
public function notify();
}
class UsersLibrary implements IObservable {
private $container;
private $contor;
//private $z;
public function __construct() {//IObserver $a) {
$this->container = array();
$this->contor = 0;
echo "<div>[constructing UsersLibrary...]</div>";
$this->addObserver(new Logger());
//$this->z = $a;
}
public function add($obj) {
echo "<div>[adding a new user...]</div>";
$this->container[$this->contor] = $obj;
$this->contor++;
$this->notify();
}
public function get($index) {
return $this->container[$index];
}
public function addObserver(IObserver $obj) {
$this->container[] = $obj;
}
public function notify() {
echo "<div>[notification in progress...]</div>";
foreach($this->container as $temp) {
//echo $temp;
#################################################################
$temp->update(); //--------ERROR
//Fatal Error: Call to a member function update() on a non-object.
#################################################################
}
//$this->container[0]->update();
//$this->z->update($this);
}
}
class User {
private $id;
private $name;
public function __construct($id, $name) {
$this->id = $id;
$this->name = $name;
}
public function getId() {
return $this->id;
}
public function getName() {
return $this->name;
}
}
class Logger implements IObserver {
public function __construct() {
echo "<div>[constructing Logger...]</div>";
}
public function update(IObservable $sender) {
echo "<div>A new user has been added.</div>";
}
}
$a = new UsersLibrary(); //new Logger());
//$a->add(new User(1, "DemoUser1"));
//$a->add(new User(2, "DemoUser2"));
$a->add("Demo");
echo $a->get(0);
//echo $a->get(0)->getName();
Your User class is not implementing interface IObserver and therefore is not forced to have the method update().
You have to instantiate a new User() in order to add it to the UsersLibrary:
$library = new UsersLibrary();
$user = new User(1, "Demo");
$library->add($user);
Also, you are mixing Users and Loggers into your UsersLibrary container. Maybe think about separating the containers for them?
You are passing a string instead of an object in your $a->add() call. You should either pass in an object, or alter the code in UserLibrary::add() to wrap it's argument in an appropriate object (or do an object lookup of it sees a string, for instance find a user with that name).
$user = new User(1, "Demo");
$a = new UsersLibrary();
$a->add($user);

Categories