I would like to know if there is anyway I can make a parent object with php, I have tried this:
new parent::__construct($var);
but it doesn't work and I get the following error in the php logs:
(..)PHP Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE or '$'(..)
see http://uk.php.net/get_parent_class
<?php
class Foo {
}
class Bar extends Foo {
protected $p;
public function __construct() {
$pc = get_parent_class();
$this->p = new $pc;
}
}
$bar = new Bar;
var_dump($bar);
(But somehow I fail to see why you would need something like that. But maybe that's just me.... ;-))
Just call the constructor of the parent class like:
$parentClassObject = new ParentClassName();
Use parent::__construct() to call the parent class constructor since it is not done automatically in PHP.
This might work:
$parentClass = get_parent_class();
$parentObject = new $parentClass();
Related
While I was creating a class in php, I experienced this error:
Parse error: syntax error, unexpected '[', expecting ',' or ';' on line 5
A simple example:
<?php
class MyClass
{
public $variable["attribute"] = "I'm a class property!";
}
?>
I already had a look at Reference - What does this error mean in PHP? but this doesn't seem to fit to my case. The problem of all other existing Questions seem to rely to an old PHP Version. But I am using PHP 5.6.3!
What can I do? Am I just sightless?
You can't explicitly create a variable like that (array index). You'd have to do it like this:
class MyClass {
// you can use the short array syntax since you state you're using php version 5.6.3
public $variable = [
'attribute' => 'property'
];
}
Alternatively, you could do (as most people would), this:
class MyClass {
public $variable = array();
function __construct(){
$this->variable['attribute'] = 'property';
}
}
// instantiate class
$class = new MyClass();
I guess you should declare it the way it is shown below :
class MyClass
{
public $variable = array( "attribute" => "I'm a class property!" );
}
Make an array first. Use the code below
<?php
class MyClass
{
public $variable = array("attribute"=>"I'm a class property!");
}
?>
HOpe this helps you
You cannot declare class members like this. Also you cannot use expressions in class member declarations.
There are two ways to achieve what you are looking for :
class MyClass
{
public $variable;
function __construct()
{
$variable["attribute"] = "I'm a class property!";
}
}
or like this
class MyClass
{
public $variable = array("attribute" => "I'm a class property!");
}
In PHP sometimes it would be nice if I could define a function or a class with a variable name like
$myfunctionname="test";
function $myfunctionname(){
//...
}
so it would create the function test()
or with classes too like:
$foo = bar;
class $foo {
// lots of complicated stuff
// ...
}
but this doesen't work. like this it would give parse errors!
Is there a solution to this?
(I know, this is not good practise, but just as a workaround, it would be handy)
EDIT: My actual problem:
I have a framework with a migration process where every migration step is in a separate php include file in a folder.
Each file contains only one migration class that contains the name of the include file.
Because the class has to have that certain name, I would like to create the name of the class to a generic name that is created by the filename constant __FILE__
Yes, you can, but I dont want you to.
$classname = "test";
eval("class {$classname}{ public function hello(){ echo \"hello!\"; } }");
$evil_class = new $classname();
$evil_class->hello(); // echo's "hello!"
now, if you don't mind me I'm going for a shower.
You can use a factory pattern:
class poly_Factory {
public function __construct() {
$class = 'poly';
return new $class();
}
}
If that is anything you want to get to.
http://net.tutsplus.com/tutorials/php/understanding-and-applying-polymorphism-in-php/
Scroll down to step 4, last part...
I know you did not ask for that, but what can your question be good for else?
No. This code throws a parse error on line 3 because of the $:
$foo = 'bar';
class $foo {
function hello() {
echo "World";
}
}
$mybar = new bar();
$mybar->hello();
Result:
Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING on line 3
And as Jan Dvorak pointed out in the comments: even if you figure out a way to do this, don't do this.
If you want to create a value object you can just use the stdClass builtin type.
$object = new stdClass;
$object->someValue = "Hello World";
echo $object->someValue;
See it in Action
If you want to assign methods then you have to use the magic __call function, here is how I would do it.
class AnonObject{
private $properties = array();
private $methods = array();
public function __get($property){
return array_key_exists($property, $this->properties)?$this->properties[$property]:null;
}
public function __set($property, $value){
if (!is_string($value) && is_callable($value)){
if ($value instanceof \Closure){
// bind the closure to this object's instance and static context
$this->methods[$property] = $value->bindTo($this,get_class($this));
} else {
// invokable objects
$this->methods[$property] = $value;
}
} else {
$this->properties[$property] = $value;
}
}
public function __call($method, $args){
if (array_key_exists($method, $this->methods)){
call_user_func_array($this->methods[$method], $args);
} else {
throw new RuntimeException("Method ".$method." does not exist on object");
}
}
}
See it In Action
Note, as stated by several other people this is bad practice. If the goal of this exercise is to compose the behavior of an instance of an object at runtime a more maintainable solution would be to use the Strategy Pattern
I have a question regarding "dynamic" class initialising, let me explain what I mean:
$class = 'User';
$user = new $class();
//...is the same as doing
$user = new User();
So... that's not the problem, but I am having some trouble doing the same while calling a static variable from a class, for example:
$class = 'User';
print $class::$name;
Which gives out the following error:
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in
Off course I have tested doing print User::$name; and that works. So class works.
Why is this and is there a way around it?
Follow up question:
Also is there any valid reasons to not use this "dynamic" way in creating classes?
This code works good on PHP 5.4.3:
<?php
class A {
public static $var = "Hello";
}
print(A::$var);
$className = "A";
print($className::$var);
?>
This is the answer from the question I linked in the comments:
You can use reflection to do this. Create a ReflectionClass
object given the classname, and then use the getStaticPropertyValue
method to get the static variable value.
class Demo
{
public static $foo = 42;
}
$class = new ReflectionClass('Demo');
$value=$class->getStaticPropertyValue('foo');
var_dump($value);
If you don't have PHP version of 5.3 and above, and you don't want to use reflection (which in my opinion is an overkill - unless you want to access multiple static properties) you can define getter function and call it via call_user_func():
class A {
public static $var = "Hello";
public static function getVar() {
return self::$var;
}
}
$className = "A";
echo call_user_func(array($className, 'getVar'));
I have a class look like below:
<?php
class theGodFather {
public function do() {
echo "the movie is nice";
}
}
$obj = new theGodFather;
echo $theGodFather->do;
When run I got the error: syntax error, unexpected T_DO, expecting T_STRING in /Applications/XAMPP/xamppfiles/htdocs/test/classes.php on line 3
what could I possibly did wrong?
You cannot use keywords as names for functions/classes/methods and constants, do is one. You can use them as variable names, however.
"do" is a keyword (can be used in a do while loop). Also you're echoing a function that returns nothing, but echoes something in it.
Rename the "do" function to "echoFunction" or whatever name you choose and then
change this:
$obj = new theGodFather;
echo $theGodFather->do;
to:
$obj = new theGodFather;
$obj->echoFunction();
The reason you wouldn't call $theGodFather->echoFunction because theGodFather is a class definition, while $obj is an actual instance of the class. You can have static methods in PHP that you can call without creating a new instance.
you have use do function in class "do" is a keyword of php and you cannot use keyword in function or class
try this
class theGodFather
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo 'a default value';
}
}
$obj = new theGodFather();
//print_r($obj);
echo $obj->displayVar();
do is a keyword, therefore the interpreter gets very very confused. :(
Choose a different function name and it works!
I have a class like
class blah extends blahblah{
private $variable = '5';
function somefunction(){
echo $variable;
}
}
this works in php 5, but not in php 4.
I get a error:
Parse error: parse error, unexpected
T_VARIABLE, expecting T_OLD_FUNCTION
or T_FUNCTION or T_VA....
I also tried with public and static. Same error.
How can I add a variable inside that class that I can access from all class functions?
private is not a valid keyword in PHP 4 change it to var $variable = '5';
also the function is wrong it should be...
class blah extends blahblah{
var $variable = '5';
function somefunction(){
echo $this->variable;
}
}
In PHP4, member variables are declared with var:
var $variable = '5';
But you still have to access it via $this->variable in your function (I think, I'm not so familiar with PHP4).
That said, if possible, upgrade! PHP4 and "OOP" is more pain than fun.
Update: Ha, found it, some documentation about Classes and Objects in PHP4.