class Student{
$db_fields = array('id','firstname','lastname')
}
Is there any way to set $db_fields array into a public variable/attribute without typing it manually like:
class Student{
$db_fields = array('id','firstname','lastname')
public $id;
public $firsname;
public $last;
}
?
I'm trying to set it using foreach but I can't make it done.
class Student{
public $db_fields;
public $id;
public $firsname;
public $last;
public function __construct($data){
$this->db_fields = $data;
}
}
$students = new Student(array('id','firstname','lastname'));
You can set it this way ..
or this way..
class Student{
public $db_fields;
public $id;
public $firsname;
public $last;
public function set_db_fields($data){
$this->db_fields = $data;
}
}
$students = new Student();
$students->set_db_fields(array('id','firstname','lastname'));
The idea is when you call that class to set Those variables with some function..
1st way is to use the constructor and 2nd way is to write 1 function only for that..
The 3rd way is as #PLB replayed with magic functions.
Yes, you can use magic method __get and __set (These methods are used to access inaccessible variables of instance. You can get further information in documentation) in your class Student.
public function __get($name) {
return $this->{$name};
}
public function __set($name, $value){
$this->{$name} = $value;
}
Now you can use it:
$obj = new Student();
$obj->db_fields = array(1,2,3); //Assign private variable.
var_dump($obj->db_fields); //Get private variable.
The only way to access an array's variable is through the array (to my knowledge) as such:
$db_fields = array('id' => 5,'firstname' => 'Paul', 'lastname' => 'Doe');
echo $db_fields->id; // would print 5.
What you're saying you want is:
$db_fields = array('id' => 5,'firstname' => 'Paul', 'lastname' => 'Doe');
echo $id; // would print 5 but that is not possible
The only instance where this works is if the array you're talking about is $_POST and $_GET with register globals, but to my knowledge it is not possible to do this with any array (and in fact it is usually not recommended to do it even with the $_POST and $_GET arrays).
EDIT:
You can actually use the extract() function on your array.
$db_fields = array('id' => 5,'firstname' => 'Paul', 'lastname' => 'Doe');
extract($db_fields);
echo $id; // if I'm not mistaken, that should work
Related
I will try to explain what I want to accomplish with this method using an example:
You have an objectPerson with the method getName() which returns PersonName.
Converting [PersonA, PersonB] into [PersonNameA, PersonNameB].
I know PHP has a method array_column to reach this with properties. But I am wondering if there is also a method to do this with objects' methods.
To expand on the usage of array_map() that #axiax mentioned in his comment, you might feed it a closure for a first argument like this:
<?php
class Person
{
private $name;
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
$personA = new Person();
$personB = new Person();
$personA->setName('bob');
$personB->setName('alice');
$objects = [
$personA,
$personB
];
$names = array_map(
function(Person $p) {
return $p->getName();
},
$objects
);
var_dump($names); // ['bob', 'alice']
I've got a private variable in my class
private $noms = array(
"HANNY",
"SYS",
"NALINE"
);
I want to access it from a static method:
public static function howManyNom($searchValue){
$ar = $this->noms;
foreach($ar as $key => $value) {
...
But as normal I cant retrieve it with $this because there's no instance on a static method.
What's the right syntax to get $noms inside my static function?
Make this attribute static too!
private static $noms = array(
"HANNY",
"SYS",
"NALINE"
);
public static function howManyNom($searchValue){
$ar = self::$noms;
foreach($ar as $key => $value) {
To access the $noms array make it static, you do that like so:
private static $noms = array();
You then access that like so:
self::$noms['some key'];
You have to make the noms static, too and access it via self::$noms.
<?php
class User {
private $id;
private $username;
public function __construct($id = null) {
$this->id = $id;
if (!is_null($this->id)) {
$this->load();
}
}
public function load() {
}
}
?>
In the 'load' method I am going to load all the information from the current user (id) But I wonder how is the best way to load all info. I could grab all data and then just assign all private variables, but I assume there must be another "cheaper" way to get all the data so I can use as such
$this->variable;
And not have to ASSIGN every single data row, I select in the load method. How?
I am assuming the following:
Each User object represents 1 row in your database
You can retrieve information for your user in an associative array:
$user = array('name' => 'John', 'age' => 20);
Then perhaps using variables variables could be a viable solution in your load() method:
foreach($user as $key => $userData){
$this->$$key = $userData; //Note the use of variables variable
}
You can assign multiple variables like this in php:
private function getUserData() {
return array("42", "JohnDoe");
}
public function load() {
list($this->id, $this->username) = getUserData();
}
I know that in C# you can nowadays do:
var a = new MyObject
{
Property1 = 1,
Property2 = 2
};
Is there something like that in PHP too? Or should I just do it through a constructor or through multiple statements;
$a = new MyObject(1, 2);
$a = new MyObject();
$a->property1 = 1;
$a->property2 = 2;
If it is possible but everyone thinks it's a terrible idea, I would also like to know.
PS: the object is nothing more than a bunch of properties.
As of PHP7, we have Anonymous Classes which would allow you to extend a class at runtime, including setting of additional properties:
$a = new class() extends MyObject {
public $property1 = 1;
public $property2 = 2;
};
echo $a->property1; // prints 1
Before PHP7, there is no such thing. If the idea is to instantiate the object with arbitrary properties, you can do
public function __construct(array $properties)
{
foreach ($properties as $property => $value)
{
$this->$property = $value
}
}
$foo = new Foo(array('prop1' => 1, 'prop2' => 2));
Add variations as you see fit. For instance, add checks to property_exists to only allow setting of defined members. I find throwing random properties at objects a design flaw.
If you do not need a specific class instance, but you just want a random object bag, you can also do
$a = (object) [
'property1' => 1,
'property2' => 2
];
which would then give you an instance of StdClass and which you could access as
echo $a->property1; // prints 1
I suggest you use a constructor and set the variables you wish when initialising the object.
I went from c# to PHP too, so I got this working in PHP:
$this->candycane = new CandyCane(['Flavor' => 'Peppermint', 'Size' => 'Large']);
My objects have a base class that checks to see if there's one argument and if it's an array. If so it calls this:
public function LoadFromRow($row){
foreach ($row as $columnname=>$columnvalue)
$this->__set($columnname, $columnvalue);
}
It also works for loading an object from a database row. Hence the name.
Another way, which is not the proper way but for some cases okay:
class Dog
{
private $name;
private $age;
public function setAge($age) {
$this->age = $age;
return $this;
}
public function getAge() {
return $this->age;
}
public function setName($name) {
$this->name = $name;
return $this;
}
public function getName() {
return $this->name;
}
}
$dogs = [
1 => (new Dog())->setAge(2)->setName('Max'),
2 => (new Dog())->setAge(7)->setName('Woofer')
];
I have a class with a static method. There is an array to check that a string argument passed is a member of a set. But, with the static method, I can't reference the class property in an uninstantiated class, nor can I have an array as a class constant.
I suppose I could hard code the array in the static method, but then if I need to change it, I'd have to remember to change it in two places. I'd like to avoid this.
You can create a private static function that will create the array on demand and return it:
class YourClass {
private static $values = NULL;
private static function values() {
if (self::$values === NULL) {
self::$values = array(
'value1',
'value2',
'value3',
);
}
return self::$values;
}
}
I put arrays in another file and then include the file wherever I need it.
I am having a really really hard time understanding your question. Here is essentially what I understood:
I need to maintain a proper set, where
no two elements are the same.
PHP does not have a set type, not even in SPL! We can emulate the functionality of a set but any solution I can think of is not pleasant. Here is what I think is the cleanest:
<?php
class Set {
private $elements = array();
public function hasElement($ele) {
return array_key_exists($ele, $elements);
}
public function addElement($ele) {
$this->elements[$ele] = $ele;
}
public function removeElement($ele) {
unset($this->elements[$ele]);
}
public function getElements() {
return array_values($this->elements);
}
public function countElements() {
return count($this->elements);
}
}
Example usage:
<?php
$animals = new Set;
print_r($animals->getElments());
$animals->addElement('bear');
$animals->addElement('tiger');
print_r($animals->getElements());
$animals->addElement('chair');
$animals->removeElement('chair');
var_dump($animals->hasElement('chair'));
var_dump($animals->countElements());