PHP Use Array as Class's property - php

no matter where i search, i never found any rule that said class's property can't be an Array, but no matter how i tried, it never worked. It is against the rule to assign ARRAY as class's property? If so, is there any workaround? Here is my code
class Imperials{
protected $Data;
function __Construct($passedData){
$this->$Data = $passedData;
echo($this->$Data['Name']);
}
}
$var = new Imperials(array('Name'='Buster','Race'='Nords'));
It would returned an error message
Fatal error: Uncaught Error: Cannot access empty property

Use $this->Data without the $ instead of $this->$Data and use => for the array.
class Imperials{
protected $Data;
function __Construct($passedData){
$this->Data = $passedData;
echo($this->Data['Name']);
}
}
$var = new Imperials(array('Name'=>'Buster','Race'=>'Nords'));

Related

Finding out the type from an uninitialized typed property

I have the following code in my User class:
class User {
public int $id = 0;
public string $code;
public string $name;
}
When assigning $code from the database, I need to find out what type the var is before I can assign it, so I use gettype(), in the __construct function for User:
foreach($data as $key => $val) {
settype($val, gettype($this->$key));
$this->$key = $val;
}
However it returns this error:
Fatal error: Uncaught Error: Typed property User::$code must not be accessed before initialization
I understand what the error message means.
Is there a way to find out the casted type of the variable before its been set?
I'm not sure what exactly you are attempting to do, and without knowing more about the whole thing I won't risk an opinion about the logic of it.
Putting that aside, using gettype() on an uninitialized typed property won't work, because the property has effectively no value at that point.
But, since the property is typed, you could get the property defined type via reflection:
class User {
public int $id = 0;
public string $code;
public string $name;
public function __construct() {
$reflect = new ReflectionClass($this);
$props = $reflect->getProperties();
foreach ($props as $prop) {
echo $prop->getType()->getName(), "\n";
}
}
}
new User();
The above would output:
int
string
string
Doing this on the fly seems like a lot of overhead, so please make sure that there is no better tool at your disposal. Doing this kind of thing on the __construct() method does not look very wise at first sight, but of course I do not know your specific constraints.
If you create a variable as
$foo;
then it is null until it is successfully initialized, so it has no type.
If it is a typed property, then it is simply uninitialized, not null. The rest of my answer contains some experiments conducted based on the information received in the comment-section. So, a variable or property is null before it is initialized, with the exception of typed properties, which are simply uninitialized.
In the comment section it was suggested that the uninitialized variable does not equal to null. So I have written this test code:
<?php
$foo;
echo var_dump($foo === null);
and executed it
It gives a warning and evaluates to true, so the uninitialized variable was indeed null.
Since yivi pointed out that the question refers to a property, I have conducted another experiment:
<?php
class Foo {
public $foo;
public function __construct() {
echo var_dump($this->foo === null);
}
}
new Foo();
and the result is

Fatal error: Uncaught Error: Call to a member function X on Y

I am trying to learn OOP PHP so much of this is new to me. I have seen other posts but havent found one that answers my question.
class Test
{
public function a(){
//getting data...
return $array;
}
public function b($array){
return true;
}
}
$test = new Test();
$x = $test->a()->b();
When I attempt the above I get the following error:
Fatal error: Uncaught Error: Call to a member function a() on array
Can someone explain why this doesnt work? a returns an array and b accepts an array.
In order to do what you're trying to do here, you'd need to use this instead:
$x = $test->b($test->a());
The second arrow in the expression
$x = $test->a()->b();
attempts to call an object method on the return value of $test->a(), which is an array as you know. It does not pass the return value of a() as an argument to b().
In order to use a syntax like ->a()->b(), a() must return an object with a method b(). If the method b() is a method from the same object, you can do that by returning $this in a(), but if it also needs to return an array, that won't work, so you won't be able to chain the methods like this.
It is possible to make it work if a() doesn't return the array, but instead stores in in an object property, and b() doesn't take an array, but instead operates on the data in the property.
class Test
{
protected $data;
public function a() {
//getting data...
$this->data = $theDataYouGot;
return $this;
}
public function b($array) {
// do something with $this->data
return true;
}
}
Personally I try to avoid this sort of thing because I think it adds unnecessary complexity and makes testing more difficult without much added benefit, but I have seen it done.

Error when using file_get_contents for class property

I get an error saying unexpected '(' when trying to do this in a class:
private $doglist = file_get_contents('dogdropdown.html');
Is that not allowed for some reason?
I also tried using a function like this:
public function getDogList(){
$list = file_get_contents('dogdropdown.html');
return $list;
}
which also didnt work. if I used include it does but doesnt inlcude it in the right place.
When you declare a class property you can only assign basic scalar values or null for variables that should reference objects. If the property needs to hold the result of some operation you either make it static or assign the result either in the constructor or a method of the class.
In order to do what you are trying to do you need the following:
class MyClass {
private $doglist;
function __construct() {
$this->doglist = file_get_contents('dogdropdown.html');
}
}

Call class method from inside array_map anonymous function

I am trying to call one of my object's methods from within an array_map anonymous function. So far I am receiving the expected error of:
Fatal error: Using $this when not in object context in...
I know why I am getting this error, I just don't know a way to achieve what I am trying to... Does anybody have any suggestions?
Here is my current code:
// Loop through the data and ensure the numbers are formatted correctly
array_map(function($value){
return $this->some_method($value,'value',false);
},$this->mssql->data[0]['results'][0]);
You can tell the function to "close over" the $this variable by using the "use" keyword
$host = $this;
array_map(function($value) use ($host) {
return $host->some_method($value,'value',false);
},$this->mssql->data[0]['results'][0]);
Also, you can call your map function from a class context and you will not receive any errors. Like:
class A {
public $mssql = array(
'some output'
);
public function method()
{
array_map(function($value){
return $this->mapMethod($value,'value',false);
},$this->mssql);
}
public function mapMethod($value)
{
// your map callback here
echo $value;
}
}
$a = new A();
$a->method();

What happens when $$[object name] is declared?

I was trying to debug a PHP script when I came across a declaration like:
$cart = new form;
$$cart = $cart->function();
What is $$cart?
What PHP does when you declare $$cart, is try to get the string value of the $cart object, and use that as the name for this variable variable. This means it'd have to call the __toString() magic method of its class.
If there is no __toString() method in the class, this will cause a catchable fatal error:
Catchable fatal error: Object of class MyClass could not be converted to string...
Otherwise, the name of the $$cart variable variable is the string value of the object as returned by that magic method.
An example with the __toString() magic method implemented (different classes/names but similar to your example calling code):
class MyClass {
public function __toString() {
return 'foo';
}
public function some_method() {
return 'bar';
}
}
$obj = new MyClass();
$$obj = $obj->some_method();
echo (string) $obj, "\n"; // foo
echo $$obj; // bar
the double $ is used for a variable variable.
essentially what this entails is the second $ along with the word is a variable the value of which is used for the name of the first $
i.e.-
$first = "second";
$second = 'Goodbye';
echo $$first; // Goodbye

Categories