Combine static var with parent's - php

This is what I'd like to be able to do:
class Test {
public static $test = 'boo';
}
class Two extends Test {
public static $test = parent::$test.'hoo';
}
// Two::$test == 'boohoo'
Well, specifically combining 2 arrays, but this illustrates it.
Is it possible?

This isn't possible because you can't evaluate anything when declaring a variable.
Something like:
class A {
$seconds_in_a_day = 60*60*24; // invalid
$seconds_in_a_day2 = 86400; // sour but valid
}
is invalid even.
You can move it to the constructor.
public function __construct() {
self::$test = parent::$test.'hoo';
}
Aside from all that .. just don't do it. Save your future self a lot of work and find another more intuitive solution :P

Related

How to reassigned a function from a reference in PHP?

Say I have a function from an Object :
class Cat {
protected $sound = 'MeOwWw~';
public function make_a_big_and_nice_sound () { echo $this->sound; }
}
$C = new Cat;
$C->make_a_big_and_nice_sound ();
Now, the function's name could be long and the content depends on some properties of the object itself so It can't be rewrite outside of the Object.
But let's say I kind of have only one cat to birth and I want to make it meow a lot of time in my code here and there. What I want to do is the following :
main.php
function please_meow = $C->make_a_big_and_nice_sound;
please_meow ();
If your method names are long there is a big chance your method is simple doing too much. A method should only do one single thing.
So you should really actually fix your code instead.
Considering you don't provide your actual code (which would have helped pointing out the actual flaw in your code) and if you really insist on doing this (you really shouldn't) you could use a closure for this:
$please_meow = function() use ($C) {
return $C->make_a_big_and_nice_sound();
};
$please_meow();
But again if you need this you are doing it wrong.
If you use PHP 5.3 or above, try this:
$please_meow = function() use($C) { $C->make_a_big_and_nice_sound(); };
$please_meow();
Now, the function's name could be long and the content depends on some properties of the object itself so It can't be rewrite outside of the Object.
But let's say I kind of have only one cat to birth and I want to make
it meow a lot of time in my code here and there
You can do something like this
class Cat
{
protected static $instance;
function __construct()
{
self::$instance = $this;
}
public static function please_meow()
{
self::$instance->make_a_big_and_nice_sound();
}
protected $sound = 'MeOwWw~';
public function make_a_big_and_nice_sound () { echo $this->sound; }
}
new Cat();
Cat::please_meow();
Cat::please_meow();
// some other codes
Cat::please_meow();

Is there any way to get value from the previous class?

<?php
class A {
var $varA;
function funcA() {
$this->varA='AAAA';
$bbb = new B();
$bbb->funcB();
}
}
class B {
function funcB() {
//### Is there any way to get value of $varA from here?
}
}
echo $aaa->funcA;
?>
Please see the code above. Is there any way to get value of $varA from funcB()? I know about global and I know I can pass it or add var $varB; to the B class and set it. I am asking is there any standard way (syntax) to just get the value?
You could make the variable in class A public and static, which would make it accessible using A::$varA.
class A {
public static $varA;
function funcA() {
self::$varA = 'AAAA';
$bbb = new B();
$bbb->funcB();
}
}
class B {
function funcB() {
// Get value of $varA from A statically
echo A::$varA;
}
}
However, I wouldn't recommend doing it this way, as order of operations becomes more important. I'd look at traditional public getters/setters and take a look at possible desing flaws leading you to needing this solution in the first place.

PHP trying to create dynamic variables in classes

I need to construct a class with alot of variables directly from the Database, For simplicity we'll name them 'userX', I've looked into ORM just a little, but its way over my head.
Essentially I thought I could use my procedural code
for ($i=0; $i<100; $i++) {
public ${'user'.$i};
}
But, in a class
class test() {
private $var1;
for ($i=0; $i<10000; $i++) {
public ${'user'.$i};
}
function __constructor .....
}
Obviously not.. but it leaves me with the same problem, how can I add $user0, $user1, $user2, etc etc, without having to type all 10k of them in..
Obviously, it would be 1000x easier to just grab the names from the Database, but again, that looks even harder to code. Should I buckle down and grab them all ORM style?
You could simply use the magic accessors to have as many instance attributes as you wish :
class test{
private $data;
public function __get($varName){
if (!array_key_exists($varName,$this->data)){
//this attribute is not defined!
throw new Exception('.....');
}
else return $this->data[$varName];
}
public function __set($varName,$value){
$this->data[$varName] = $value;
}
}
Then you could use your instance like this :
$t = new test();
$t->var1 = 'value';
$t->foo = 1;
$t->bar = 555;
//this should throw an exception as "someVarname" is not defined
$t->someVarname;
And to add a lot of attributes :
for ($i=0;$i<100;$i++) $t->{'var'.$i} = 'somevalue';
You could also initialize a newly created instance with a given set of attributes
//$values is an associative array
public function __construct($values){
$this->data = $values;
}
Try $this->{$varname}
class test
{
function __construct(){
for($i=0;$i<100;$i++)
{
$varname='var'.$i;
$this->{$varname}=$i;
}
}
}
You can use variable variables ($$var) - content of one variable is used as a name for other variable (double $$)
Therefore not $this->varname but $this->$varname.
class test
{
for($i=0;$i<100;$i++)
{
$varname='var'.$i;
$this->$varname=$i;
}
}
This will dynamically create 100 variables with names $var0, $var1 ...

calling class method (with constructors) without object instantiation in php

Ive looked and tried but I can't find an answer.
In PHP, is it possible to call a class' member function (when that class requires a constructor to receive parameters) without instantiating it as an object?
A code example (which gives errors):
<?php
class Test {
private $end="";
function __construct($value) {
$this->end=$value;
}
public function alert($value) {
echo $value." ".$this->end;
}
}
//this works:
$example=new Test("world");
$example->alert("hello");
//this does not work:
echo Test("world")::alert("hello");
?>
Unfortunately PHP doesn't have support to do this, but you are a creative and look guy :D
You can use an "factory", sample:
<?php
class Foo
{
private $__aaa = null;
public function __construct($aaa)
{
$this->__aaa = $aaa;
}
public static function factory($aaa)
{
return new Foo($aaa);
}
public function doX()
{
return $this->__aaa * 2;
}
}
Foo::factory(10)->doX(); // outputs 20
Just do this (in PHP >= 5.4):
$t = (new Test("Hello"))->foo("world");
I, too, was looking for a one-liner to accomplish this as part of a single expression for converting dates from one format to another. I like doing this in a single line of code because it is a single logical operation. So, this is a little cryptic, but it lets you instantiate and use a date object within a single line:
$newDateString = ($d = new DateTime('2011-08-30') ? $d->format('F d, Y') : '');
Another way to one-line the conversion of date strings from one format to another is to use a helper function to manage the OO parts of the code:
function convertDate($oldDateString,$newDateFormatString) {
$d = new DateTime($oldDateString);
return $d->format($newDateFormatString);
}
$myNewDate = convertDate($myOldDate,'F d, Y');
I think the object oriented approach is cool and necessary, but it can sometimes be tedious, requiring too many steps to accomplish simple operations.
You can't call an instance-level method without an instance. Your syntax:
echo Test("world")::alert("hello");
doesn't make a lot of sense. Either you're creating an inline instance and discarding it immediately or the alert() method has no implicit this instance.
Assuming:
class Test {
public function __construct($message) {
$this->message = $message;
}
public function foo($message) {
echo "$this->message $message";
}
}
you can do:
$t = new Test("Hello");
$t->foo("world");
but PHP syntax doesn't allow:
new Test("Hello")->foo("world");
which would otherwise be the equivalent. There are a few examples of this in PHP (eg using array indexing on a function return). That's just the way it is.
For this you can do a
https://www.php.net/manual/en/reflectionclass.newinstancewithoutconstructor.php
reflect your class and trigger the new instance without constructor.
Here a sample code:
<?php
class Test {
private $end="";
function __construct($value) {
$this->end=$value;
}
public function alert($value) {
echo $value." ".$this->end;
}
public function end($value) {
$this->end = $value;
return $this; // return Test object so that you can chain to other function method.
}
}
// Solution #1:
// reflect your class.
$reflector = new \ReflectionClass('Test');
// Then create a new instance without Constructor.
// This will ignore the constructor BUT it will create a new instance of class Test.
$say = $reflector->newInstanceWithoutConstructor();
// use end method that will return the Test object, then you can chain the alert()
$say->end('World!')->alert("Hello"); // output: Hello World!
?>
// this does not work:
echo Test("world")::alert("hello");
// works, as you are calling not to an object of the class, but to its namespace
echo Test::alert("hello");

Dynamically creating instance variables in PHP classes

I'm not sure if this is a trivial questions but in a PHP class:
MyClass:
class MyClass {
public $var1;
public $var2;
constructor() { ... }
public method1 () {
// Dynamically create an instance variable
$this->var3 = "test"; // Public....?
}
}
Main:
$test = new MyClass();
$test->method1();
echo $test->var3; // Would return "test"
Does this work?? How would I get this to work? Ps. I wrote this quickly so please disregard any errors I made with setting up the class or calling methods!
EDIT
What about making these instance variables that I create private??
EDIT 2
Thanks all for responding - Everyone is right - I should have just tested it out myself, but I had an exam the next morning and had this thought while studying that I wanted to check to see if it worked. People keep suggesting that its bad OOP - maybe but it does allow for some elegant code. Let me explain it a bit and see if you still think so. Here's what I came up with:
//PHP User Model:
class User {
constructor() { ... }
public static find($uid) {
$db->connect(); // Connect to the database
$sql = "SELECT STATEMENT ...WHERE id=$uid LIMIT 1;";
$result = $db->query($sql); // Returns an associative array
$user = new User();
foreach ($result as $key=>$value)
$user->$$key = $value; //Creates a public variable of the key and sets it to value
$db->disconnect();
}
}
//PHP Controller:
function findUser($id) {
$User = User::find($id);
echo $User->name;
echo $User->phone;
//etc...
}
I could have just put it in an associative array but I can never correctly name that array something meaningful (ie. $user->data['name'] ... ugly.) Either way you have to know what is in the database so I do not really understand what the argument is that its confusing, especially since you can just var dump objects for debugging.
Why dont you just write the code and see for yourself?
<?php
class Foo
{
public function __construct()
{
$this->bar = 'baz';
}
}
$foo = new Foo;
echo $foo->bar; // outputs 'baz'
and
var_dump($foo);
gives
object(Foo)#1 (1) {
["bar"] => string(3) "baz"
}
but
$r = new ReflectionObject($foo);
$p = $r->getProperty('bar');
var_dump($p->isPublic());
will throw an Exception about 'bar' being unknown, while
$r = new ReflectionObject($foo);
$p = $r->getProperties();
var_dump($p[0]->isPublic());
will return true.
Now, should you do this type of assignment? Answer is no. This is not good OOP design. Remember, OOP is about encapsulation. So, if bar is describing some public property of the class, make it explicit and declare it in your class as public $bar. If it is supposed to be private declare it as private $bar. Better yet, dont use public properties at all and make them protected and provide access to them only through getters and setters. That will make the interface much more clearer and cleaner as it conveys what interaction is supposed to be possible with an object instance.
Assigning properties on the fly here and there across your code, will make maintaining your code a nightmare. Just imagine somewhere along the lifecylce of Foo someone does this:
$foo = new Foo;
$foo->monkey = 'ugh';
echo $foo->monkey; // outputs 'ugh'
Now, from looking at the class definition above, there is absolutely no way, a developer can see there is now a monkey patched into Foo. This will make debugging a pain, especially if code like this is frequent and distributed across multiple files.
Yes that will indeed work. Auto-created instance variables are given public visibility.
yes that works as you'd hope/expect.
I you wanted to make private variables on the fly you could use php magic functions to emulate this, e.g
MyClass
<?php
class MyClass {
public $var1;
public $var2;
private $data = array();
public function __get($key) {
// for clarity you could throw an exception if isset($this->data[$key])
// returns false as it is entirely possible for null to be a valid return value
return isset($this->data[$key]) ? return $this->data[$key] : null;
}
public function __set($key, $value) {
$this->data[$key] = $value;
}
}
?>
Main
<?php
$test = new MyClass();
$test->myVar = 'myVar is technically private, i suppose';
echo $this->myVar; // 'myVar is technically private
?>
Although these dynamically created variables are technically private, they are infact publicly accessible... i cannot image the purpose for wanting to dynamically create private instance variables. I would question your design.
Did you try it?
It is possible but you might get strict errors. If you dynamically need to create these variables, you are probably doing something wrong.
You should either change this into a function:
function var($no) { .. }
or use __get (http://ca.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members)

Categories