How would I rewrite this getter as a setter? - php

I have only started PHP 3 weeks ago so be gentle with me :)
I understand that the method should accept an array index and some value as parameters to use them to update the array but I have no idea of the syntax and have tried so many times now.
I'm not sure if I can still display the array inside the method?
Or should it be outside the method but inside the class?
Any help would be awesome guys.
Best,
Derek.
<?php
class Names{
public $Names = array("Derek", "Paddy", "Des", "Billy" , "Jack");
public function getElement($IndexParameter){
return $this->Names[$IndexParameter];
}
}
$obj = new Names;
echo $obj->getElement(4);
?>

Here you go:
public function setElement($IndexParameter, $NewName) {
$this->Names[$IndexParameter] = $NewName;
}
Usage:
$obj->setElement(4, "Bilbo");
Note: I've kept your style, although I would generally recommend using InitialCaps for class names.

Mark $Names property as protected or private to prevent direct access to it.
class Names{
protected $Names = array("Derek", "Paddy", "Des", "Billy" , "Jack");
public function getNames($IndexParameter){
return $this->Names[$IndexParameter];
}
public function setNames($IndexParameter, $NewName) {
$this->Names[$IndexParameter] = $NewName;
}
}

Related

How to create sub-variables in PHP class

I started using OOP in PHP for first time, and I dont know how to achieve the following structure for my variables:
$this->myData->generalData->title;
$this->myData->generalData->description;
$this->myData->amount;
$this->myData->addNewData();
Up till now, what I am achieving is a normal variable inside a class:
$this->variablename
I tried doing this code, but it's not working at all:
$this->CDNE = "CDNE";
$this->CDNE->FOLDER = "hello man";
Can you explain me, how all this works?
Just to ilustrate my comment. Doing it with sub-objects could be something like this (a very basic example without attributes initialization):
class GeneralData{
public $title;
public $description;
}
class MyData{
public $generalData;
public $amount;
function __construct(){
$this->generalData = new GeneralData();
}
function addNewData(){
}
}
class MainClass{
public $myData;
function __construct(){
$this->myData = new MyData();
}
}

Adding an array of objects to another array in codeigntier PHP?

im using codeigntier framework im trying to solve a problem to do with retrieving information from a database for example:
model.php:
public function read(){
$query = $this->db->get('table');
return $query->result();
}
controller.php:
public function doSomething () {
$exampleArray['name'] = "Bob's Database";
$getModel = $this->load->model('model','getData');
$modelData = $this->getData->read();
// i want to assign the the $modelData to a array element like so
$exampleArray['modelData'] = $modelData // here's where im stuck :(
}
thanks for your help!!
p.s. this is not an error, its just a question :)
}
If you want to be able to access $exampleArray outside of that method, you'll have to do one of two things:
a) set it as a class variable
class MyClass {
public $exampleArray;
.
.
.
}
then refer to it using
$this->exampleArray['index']
or b) pass it by reference into your doSomething() function:
public function doSomething(&$exampleArray) { ... }
The php manual has a section on variable scope that should help you better understand this.

PHP Class: Array deinitialized after constructor?

Im making a class in php, but Im having some problems with one of the class variables. I declare a private variable, then in the constructor set it. However, later in the class I have a method that uses that variable. The variable in this case is an array. However, the method says the array is blank, but when I check it in the constructor, it all works out fine. So really the question is, why does my array clear, or seem to clear, after the constructor?
<?php
class Module extends RestModule {
private $game;
private $gamearray;
public function __construct() {
require_once (LIB_DIR."arrays/gamearray.php");
$this->gamearray = $gamesarray;
$this->game = new Game();
$this->logger = Logger::getLogger(__CLASS__);
$this->registerMethod('add', array(Rest::AUTH_PUBLIC, Rest::AUTH_USER, Rest::AUTH_ADMIN), true);
$this->registerMethod('formSelect', array(Rest::AUTH_PUBLIC, Rest::AUTH_USER, Rest::AUTH_ADMIN), false);
}
public function add(){
$game = Utility::post('game');
}
public function formSelect(){
$gamename = Utility::get('game');
$this->$gamearray[$gamename];
}
}
The array is pulled in from another file because the array contains a lot of text. Didn't want to mash up this file with a huge array declared in the constructor. The scrolling would be tremendous. Any explanation would be nice, I like to understand my problems, not just fix em'.
You have a typo:
public function formSelect(){
$gamename = Utility::get('game');
$this->gamearray[$gamename]; // Remove the $ before gamearray
}
Moreover, in your case, include is better than require_once.
If you want to go deeper, you could rewrite $gamearray assignment like this:
// Module.php
$this->gamearray = include LIB_DIR.'arrays/gamearray.php';
// gamearray.php
return array(
// Your data here
);

PHP - passing variable from one object to another troubles

I've recently started to work with OO PHP. As a training practice I'm trying to write some simple classes. I have trouble passing a variable from one to another class. Is it even possible?
class group
{
public $array = array();
public function person($name,$surname)
{
$this->person = new person($name,$surname);
}
public function __destruct()
{
print_r($this->array);
}
}
class person
{
public function __construct($name,$surname)
{
$this->name = $name;
$this->surname = $surname;
}
}
$A = new group();
$A->person("John","Doe");
What I want to archieve here is to pass person as another member of group (by simply putting it in group array) for further modifications and sorting. Been googling around but found nothing.
Please forgive me if it's a dumb one. ;)
I'm not sure I totally understand but I think you want:
Class group {
public $members=array();
public function person($name,$surname) {
$this->members[]=new person($name,$surname);
//Creates a new person object and adds it to the internal array.
}
/*...*/
}
A better alternative (seperation of intent) would be:
Class group {
public $members=array();
public function addPerson(person $p) {
$this->members[]=$p;
//Avoids this function need to know how to construct a person object
// which means you can change the constructor, or add other properties
// to the person object before passing it to this group.
}
/*...*/
}
The fix is changing
public function person($name,$surname)
{
$this->person = new person($name,$surname);
}
to
public function person($name,$surname)
{
$this->array[] = new person($name,$surname);
}
$this->person is not being stored in the array otherwise, and is overwritten with each call.
Your group class could improve it's OO by:
changing $array to be more descriptively named
changing the function name person to something more meaningful, like add_person
You should define your properties ('name', 'surname') and give them a suitability visibility
class group
{
public $array = array();
public name;
public surname;
...
Reference: http://php.net/manual/en/language.oop5.visibility.php

PHP: Use variable name to call static function on Singleton Object

I need to call a static function from an object using the Singleton design, but using a variable as the class name.
The best way, $class::getInstance();, is only available in PHP 5.3, and the other way I found, call_user_func(array($class, 'getInstance'));, results in the maximum execution time being breached. Does anyone know why this is happening, or of a way for this to work / a workaround?
I know that this is not the best way for things to be done, and the Singleton design pattern would not be my first choice, but unfortunately it's not up to me.
Thanks in advance to anyone who contributes :)
I include the rest of the code involved:
abstract class Library
{
protected function __construct(){}
final private function __clone(){}
final public static function &getInstance()
{
static $libs = array();
$lib = get_called_class();
if(!isset($libs[$lib])) $libs[$lib] = new $lib();
return $libs[$lib];
}
}
public function &loadLibrary($lib)
{
// Filter $lib, and load the library class file...
// Following only works in PHP 5.3
// return $lib::getInstance();
// Following results in maximum execution time being breached.
return call_user_func(array($lib, 'getInstance'));
}
}
$someLibrary =& loadLibrary('someLibrary');
someLibrary.php:
class someLibrary extends Library
{
protected function __construct(){}
// Code...
}
Soulmerge make a valid point saying that get_called_class() is only in PHP 5.3, and therefore I must be using it, but alas, I just cheat my way round things as I usually do (Thanks to Chris Webb from http://www.septuro.com/ for the code - far too complex to be any of my own!).
if(!function_exists('get_called_class'))
{
class classTools
{
static $i = 0;
static $fl = null;
static function get_called_class()
{
$bt = debug_backtrace();
if(self::$fl == $bt[2]['file'].$bt[2]['line']) self::$i++;
else {
self::$i = 0;
self::$fl = $bt[2]['file'].$bt[2]['line'];}
$lines = file($bt[2]['file']);
preg_match_all('/([a-zA-Z0-9\_]+)::'.$bt[2]['function'].'/', $lines[$bt[2]['line']-1], $matches);
return $matches[1][self::$i];
}
}
function get_called_class()
{
return classTools::get_called_class();
}
}
I shall go over all my code again, as there must be a loop somewhere. Back to the drawing board I go :(
You should start by determining what it is that takes you into an infinite loop. Does your constructor (someLibrary::__construct()) have any code that directly/indirectly calls Library::getInstance(), for example?
EDIT get_called_class() was introduced in PHP 5.3, so if your code actually works, you're already running 5.3
you could try to solve this with eval().
To get you an idea:
$theVar = "relvantClassName";
$someObject = eval($theVar::getInstance());
$result = $someObject->performAction();

Categories