Link to home
Start Free TrialLog in
Avatar of rgb192
rgb192Flag for United States of America

asked on

create many instances of an object with different usernames

  $m_instance = new mam($config);
  $m_instance->default_username='user1';
  $m_instance->default_username='anotherUser';
  $m_instance->default_username='anotherUser2';
 // $m_instance->default_username='bob';
 //many more users coming soon
  $m_instance->default_password='password';
  //do stuff
  

Open in new window

 
  many users and I need to manually comment out usernames and run code many times
 
  maybe something like this (but this is random and I want to be sure all the usersnames are run.  And this does not create a new instance):
 
  $input = array(
  'user1','anotherUser', 'anotherUser2','bob'
);

// SELECT ONE AT RANDOM
shuffle($input);
$pick  = array_pop($input);

Open in new window


and some increment to create a new instance
$i++;
$m_instance[$i]
or
$m_instance[$pick] where $pick is the chosen $input from $input array is the username
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

There are two ways to create an object instance.  You can use the new keyword or you can clone an existing object.  An array of objects is a very, very useful data structure.

You cannot create a new object instance with an assignment operator.  You will only create a new pointer to the same old object.  This is very different from procedural PHP, where the assignment operator creates a new and distinct variable.  You might want to review this article for some more information on the way references and variables interact.
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_12310-PHP-Variables-and-References.html
Avatar of rgb192

ASKER

I read your article and am learning about clone. I have a class that is called that has properties username, password and methods. I just have same password to make it easier. I am not a good enough coder to start editing class to allow clone.
Here is an example of clone in action...

<?php // RAY_temp_clone.php
error_reporting(E_ALL);
echo '<pre>';

// DEMONSTRATE OBJECT ORIENTED CLONE
// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28315794.html


Class Person
{
    // CONSTUCTOR MAKES THE NAME A PROPERTY OF THE OBJECT
    public function __Construct($name)
    {
        $this->name = $name;
    }
}

// CREATE AN INSTANCE OF PERSON
$ray = new Person('Ray');
var_dump($ray);

// CREATE A NEW POINTER TO THE $ray OBJECT
$new = $ray;

// MUTATE THE $ray OBJECT BY USING THE $new POINTER
$new->name = 'Fred';
var_dump($ray);

// CLONE THE OBJECT
$fred = clone $ray;

// MUTATE THE $ray OBJECT
$ray->name = 'rgb192';

// SHOW THE TWO OBJECTS
var_dump($fred, $ray);

Open in new window

Avatar of rgb192

ASKER

Where is the password. Is this why you clone, because password is the same?
Not really.  You clone because you want a separate object, but you do not want to create new objects every time.  Perhaps some properties of the object need to match another object and some properties do not.  Run this script and compare its output to the version above.

<?php // RAY_temp_clone.php
error_reporting(E_ALL);
echo '<pre>';

// DEMONSTRATE OBJECT ORIENTED CLONE
// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28315794.html


Class Person
{
    // CONSTUCTOR MAKES THE NAME A PROPERTY OF THE OBJECT
    public function __Construct($name)
    {
        $this->name     = $name;
        $this->password = 'Biden';
    }
}

// CREATE AN INSTANCE OF PERSON
$ray = new Person('Ray');
var_dump($ray);

// CREATE A NEW POINTER TO THE $ray OBJECT
$new = $ray;

// MUTATE THE $ray OBJECT BY USING THE $new POINTER
$new->name = 'Fred';
var_dump($ray);

// CLONE THE OBJECT
$fred = clone $ray;

// MUTATE THE $ray OBJECT
$ray->name = 'rgb192';

// SHOW THE TWO OBJECTS
var_dump($fred, $ray);

Open in new window

Avatar of rgb192

ASKER

I understand how $fred is unchanged because clone
and
$ray->name='rgb192' changes $ray and $new

but I can not relate to my example of iterating through array of usernames, all with a the same password and instantiating object foreach
SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
greetings  rgb192, ,  Ypou seem to be thinking about The Class and Object you need with a certain "Output" and-or web Page Result, in a way that will not do you much good. As You Have this code -

 $m_instance = new mam($config);
  $m_instance->default_username='user1';
  $m_instance->default_username='anotherUser';
  $m_instance->default_username='anotherUser2';

what you need is a Class definition and an Object that can accept the Input of many Users, instead of just one user Like -
$m_instance->default_username='anotherUser2'; So you can Have a single instances to Handle ALL (many) of the users from a DataBase Select.

You can have Class info-values Storage (properties) that are arrays or objects that you can place ALL of the Users in with code like -
 $m_instance = new mam($config);
$m_instance->addUser('user1', 'Password1');
$m_instance->addUser('anotherUser', 'Password2');
$m_instance->addUser('ThirdUser',  'Password3');

and then get each user out with
$array1 = $m_instance->getUser(0); // gets user name and password for "user1"
$array2 = $m_instance->getUser(1);

I have found it as VERY USEFUL to have array access for my Class Object as -
$m_instance[$i]

There is a PHP interface arrayaccess  , which can greatly simplify and present an Understandable way to access multiple (many users) Object info-Data, like several many USERS, please see the PHP manual at -
http://www.php.net/manual/en/class.arrayaccess.php

Ask questions If you need more info or code
You have not posted here yet, I did this code for a simple example that would be much better, because it uses a SINGLE object as a container for all of the many user "names" and "passwords", you can have an array of arrays to initiate the object and place Many Users into this when you make the Object with -
$aryU = array("First\vPWord", "Second\vPassword", "Third\vPassW");
$users1 = new usersNP($aryU);

I have several comments for explanation of some of the code work in this usersNP Class , called it usersNP for users Name Password.
class usersNP {
/* 3 pubic properties, $obj->usersAry (array) stores ALL added arrays numerically 0-1-2-3
 $obj->count tells you the total number of elements in $obj->usersAry
 $obj->lookup (array) an Efficient way to use the user "Name" to
    get the number to find the $obj->usersAry for that name */
public $count = 0, $usersAry = array(), $lookup = array();

// the object initialization __construct( ) takes an Array with
// all of the New added Arrays OR Strings with \v as a CSV like "Name\vPassword"
public function __construct(array $users = array()) {
    if(count($users) < 1) return;
    foreach($users as $value) {
        if (is_string($value)) $value = explode("\v", $value);
        if(count($value) < 2) continue; // ERROR can Not add arrays less than 2
        $this->usersAry[] = $value; // copy new array into usersAry
//put name $value[0] into lookup and set access number with $this->count increase $this->count with ++
		$this->lookup[$value[0]] = $this->count++;
        }
    }

public function addUser($name, $password) {
// add new array with name and password to usersAry
    $this->usersAry[] = array($name, $password);
    $this->lookup[$name] = $this->count++;// set lookup "name" and increase count
    }

public function getUser($in) {
// you can find user array with the the element Number OR the user "name" string
    if (is_string($in) && (isset($this->lookup[$in])))
        $in = $this->lookup[$in];// change $in from string to integer with $this->lookup[$in]
	
    if (isset($this->usersAry[$in])) {// only return VALID requests
        return $this->usersAry[$in];
        } else return null; // return a FALSE value as nuul ti indicate FAILURE
    }

public function findPassword($name) {
// Inter the string user "name" and if $name a Key in $this->lookup return password
    return isset($this->lookup[$name]) ? $this->usersAry[$this->lookup[$name]][1] : null;
    }
}// end of class UsersNP

Open in new window

I really do not know what other operations you need for the users, but this class is straight forward and relatively simple, the only complex added is the lookup array to find the numeric array number with a look-up string name.

Below is code to use this class -
$aryU = array("First\vPWord", "Second\vPassword", "Third\vPassW");
$users1 = new usersNP($aryU);// create object with user array

$users1->addUser('Fourth', '4LOCO!-??');// add a new user

echo 'First user name from usersAry= '.$users1->usersAry[0][0];

$aryU =$users1->getUser('Second');// use string here
if($u = $users1->getUser(3))// use number here and error test for success
   echo '<br />usersNP getUser name is '.$u[0].', , , passw is '.$u[1].', , user "Second" passw= '.$aryU[1].'<br />';
   else echo 'BAD getUser';

$u = $users1->findPassword('Third');// get the password for user name 'Third'
echo '<br />findPassword is '.$u;

Open in new window

The class which implements arrayaccess would be more to code and understand, but you can access it with the [ ] as -
$aryU = array(array('uZero','Word','Method1'),array('Pat','Password','Method2'),array('MeMeMe','PassW','Method3'));

$users1 = new userList($aryU); // Create a New Instance of userList with "new" add $aryU to List
// IMPORTANT! ! the $users1 is an Object NOT an Array! It can NOT do the normal PHP Array Functions like "count( )"

echo '<br />First User List name is '.$users1[0][0];// access object $users1 like an array with $users1[ ]

Open in new window

Avatar of rgb192

ASKER

output of Ray's code:
Array
(
    [0] => User Object
        (
            [username:protected] => user1
            [password:protected] => SAME
        )

    [1] => User Object
        (
            [username:protected] => anotherUser
            [password:protected] => SAME
        )

    [2] => User Object
        (
            [username:protected] => anotherUser2
            [password:protected] => SAME
        )

    [3] => User Object
        (
            [username:protected] => bob
            [password:protected] => SAME
        )

)

Open in new window


my edit of Ray's code (runs but is this correct coding practice?)
<?php // RAY_temp_rgb192.php
error_reporting(E_ALL);
echo '<pre>';

// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28315794.html

$input = array(
  'user1','anotherUser', 'anotherUser2','bob'
);

Class mam
{
  //public $username; Can run without declaring properties (which is a security risk)
  public function doSomething(){
    echo '<br>username: '.$this->username.' in class:'. __CLASS__. ' in function: '.__FUNCTION__.'<br>';
  }
  
}

Class User
{
    protected $username = 'NOT SET';
    protected $password = 'SAME';
    public function __construct($x)
    {
      $m_instance = new mam($config);  
      $m_instance->username= $this->username = $x;
      $m_instance->password= $this->password;
      $m_instance->doSomething();   
        
    }
}

foreach ($input as $name)
{
    $out[] = new User($name);
}
print_r($out);

Open in new window


ouput of my edit of Ray's code:
username: user1 in class:mam in function: doSomethingusername: anotherUser in class:mam in function: doSomethingusername: anotherUser2 in class:mam in function: doSomethingusername: bob in class:mam in function: doSomethingArray
(
    [0] => User Object
        (
            [username:protected] => user1
            [password:protected] => SAME
        )

    [1] => User Object
        (
            [username:protected] => anotherUser
            [password:protected] => SAME
        )

    [2] => User Object
        (
            [username:protected] => anotherUser2
            [password:protected] => SAME
        )

    [3] => User Object
        (
            [username:protected] => bob
            [password:protected] => SAME
        )

)

Open in new window



I will analyze code of Slick812 next comment.
Avatar of rgb192

ASKER

Slick182:
$aryU = array("First\vPWord", "Second\vPassword", "Third\vPassW");
$users1 = new usersNP($aryU);// create object with user array


I do not think I am a good enough coder to modify the code to call my class mam() as I did in the comment above
https://www.experts-exchange.com/questions/28315794/create-many-instances-of-an-object-with-different-usernames.html?anchorAnswerId=39737854#a39737854


Adding the second instance snippet
Fatal error: Class 'userList' not found in C:\Users\Acer\Documents\NuSphere PhpED\Projects\noname282.php on line 64
OK rgb192,  I really do not understand what your goal is for this learning exercise code work, or what you need to end up with as a PHP Class,, ,
you give this as an example -
$m_instance->default_username='anotherUser2';

and then you give this -
  $input = array(
  'user1','anotherUser', 'anotherUser2','bob'
);

// SELECT ONE AT RANDOM
shuffle($input);
$pick  = array_pop($input);

I can not see any relation to your code or Ray's code as some Random $pick used in the new object.

AND! !  You use a very undefined and confusing $input = array(
as it seems to have 4 "User Names" BUT NO "User Passwords"? ? what is that about?

But my main problem is that in your first code examples you have No Functioning at all, I can not see anything about what this CLASS you want to create is suppose to do (functional, as do something with methods) after you create it as object with the new operator? ?
Ray added a method as -
  public function __construct($x)

But even with his code AND your code I do not know what this Class is suppose to do, but maybe you are just trying to see how to do basic object creation? without any real programming use at all? ? ?
Avatar of rgb192

ASKER

I can not see any relation to your code or Ray's code as some Random $pick used in the new object.

I run the code many times so that all usernames are run.


And did I edit the code from Ray properly in
https://www.experts-exchange.com/questions/28315794/create-many-instances-of-an-object-with-different-usernames.html?anchorAnswerId=39737854#a39737854
OK,  rgb192, ,  I am really glad that you are asking questions and trying to Understand what your code is doing and HOW to use Object Oriented Code practices and understand your code for better code work.

BUT you do not seem to understand that in rays code you do NOT use Object Oriented Code practices for this line of code -
$out[] = new User($name);

$out[] is an ARRAY,
$out[] is NOT an OBJECT! !
this is perfectly correct code practices, however your coding as $out[] brings to having ARRAY code, not Object Oriented Code.

ALSO in that code there is this line-
$m_instance->password= $this->password;
which seems to have ALL passwords be identical strings as [password:protected] => SAME,
which is not a practical-usable way to have good object oriented code.
However, you seem to think that if your PHP code runs without errors, then it is somehow "GOOD" code.
And it is good code, for this example, However in any usable code that actually uses Passwords, you will need another Class setup for having a way to use an INPUT array with user names, PAIRED with user passwords, which is what my code having an INPUT as an array -
public function __construct(array $users = array()) {

 This INPUT array I use, has each and every user name joined with a user password, , so you do not end up with -
"which seems to have ALL passwords be identical strings".

if you only need to have different user names, and not different user passwords, then award Ray the correct answer for this question and move on to something else,
but if you need to have a usable Class code with names AND passwords, then you should have spent more time on thinking about your original question and your original Input as -
$input = array('user1','anotherUser', 'anotherUser2','bob');
which does NOT HAVE any PASSWORDS.
Ray has given you some correct code for your original question,
but the failing here is you, not asking a good question about HOW to use Object Oriented Code practices.
It is my opinion, that You can not learn to have good Object Oriented Code practices with a Class that does not do anything, , that does not have any methods with a purpose.
Avatar of rgb192

ASKER

$out[] is an ARRAY,
$out[] is NOT an OBJECT! !
this is perfectly correct code practices, however your coding as $out[] brings to having ARRAY code, not Object Oriented Code.
Then how should Ray's code be edited to have $out as an object or whatever you suggest?



ALSO in that code there is this line-
$m_instance->password= $this->password;
which seems to have ALL passwords be identical strings as [password:protected] => SAME,
which is not a practical-usable way to have good object oriented code.
However, you seem to think that if your PHP code runs without errors, then it is somehow "GOOD" code.
And it is good code, for this example, However in any usable code that actually uses Passwords, you will need another Class setup for having a way to use an INPUT array with user names, PAIRED with user passwords, which is what my code having an INPUT as an array -
public function __construct(array $users = array()) {




I read about constructors taking 1 or 2 parameters.  
In this case the constructor should take 2 parameters (username, password)
but for this example the passwords are the same so only username


class mam{
	public function __construct($config = array())
	{ 
           ...
        }
...
}

Open in new window


class mam has many properties and methods but I do not want to edit the class, I did not create class mam. I want to pass different users

$config is from a config file which assumed one user with one password
where if I manually set properties (username, password, ...) the $config values are overwritten.
I read your last post, and can not understand what you are trying to accomplish with any thing you say here!
even Ray seems to not get "what you may want to do" and in his post ID: 39714033, he says= "I may be misunderstanding the question,"

you say - "class mam has many properties and methods but I do not want to edit the class, I did not create class mam. I want to pass different users"

if you can not change the class mam, then you have to use it as it is, but you say you want to  "pass different users"

the $config is apparently a file read from a config file to array,
SO if you need to "pass different users", you may should change the config file, as in "edit the config file", if you can not do that, , or do not want to do that then you may can change $config array to "add users", , but you seem to want to "Change the $m_instance-> default_username", , but you also seem to think that this "default_username" adds to the user names, but it DOES NOT ADD TO $m_instance user names! !


rgb192 I feel bad for you since you seem to Not Understand what this "class mam" is doing, but me and Ray can NOT understand what this "class mam" is or does from the small amount of information you give about "class mam", you seem to completely confused Ray in your question here, and I am also confused! have you ever shown the source code for this  "class mam" Class?
Avatar of rgb192

ASKER

SO if you need to "pass different users", you may should change the config file, as in "edit the config file"

yes I can edit the config file copy and pasting each of my 4 users to
$config['default_username']='bob'
and running code 4 times

or I can uncomment line 5 to allow bob to be the $m_instance->default_username
  $m_instance = new mam($config);
  $m_instance->default_username='user1';
  $m_instance->default_username='anotherUser';
  $m_instance->default_username='anotherUser2';
 // $m_instance->default_username='bob';
 //many more users coming soon
  $m_instance->default_password='password';
$m_instance->method();

Open in new window


line 8 is the method which is run in the 'black box'.  I do not understand how the class mam works, but I do know when I have set properties of the instance $m_instance: different results are returned foreach $m_instance->default_username



Thank you for helping ask the question better.
I think my question is:
I want all my usernames (or $m_instance_default_username) to be parameters of the  $m_instance->method() which takes no parameters but knows the $this->default_username from the class constructor.

My current solution is randomly picking from the 4 (soon to be more in the future) usernames and running the code many times to insure that all usernames are run.


Is my edit of Ray's solution good code?
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rgb192

ASKER

foreach ($input as $uName) {
  $m_instance->default_username=$uName;
  $m_instance->default_password='password';
  $m_instance->method();
  }

Open in new window


Should
$m_instance = new mam($config);
be in the foreach loop
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rgb192

ASKER

I used procedural code to loop through the users.

https://www.experts-exchange.com/questions/28336179/Related-question-that-allowed-me-to-create-this-procedural-code-to-loop-through-all-the-users.html

Thanks for solving the requirement.

I would like to make this code object oriented.