PHP - a simple class that can't run - php

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!

Related

instantiating a object on the fly a static method?

I'm not so sure what the following object instantiation is called but it comes from a article that i'm reading.
class foo
{
function out()
{
return 'hello';
}
}
echo (new foo())->out();
The object is instantiated automatically and calls the out method. But what i dont really understand is when i rename the out() method into a fictitious method i get an error like this:
example:
class foo
{
function out()
{
return 'hello';
}
}
echo (new foo())->ou();
Fatal error: Call to undefined method foo::ou() in ...
Is this method somehow being called as a static method?
The :: does not stand for static method, this is a missconception. The :: is a "scope resolution operator", it denotes the identification of a method by its class predicated full name.
So this simply means: "method 'ou' as defined by class 'foo'". Not more, not less.
No. The error just indicates that the method doesn't exist. It always shows the :: for this error, no matter whether you call the method in a static way or not. You would get the same error if you changed the code to:
$foo = new foo();
echo $foo->ou();
Second code example as per request in comments:
$moo = new moo(); // Parentheses optional, I guess
$foo = new foo($moo);
$foo->out();

Adding variables inside constants

I'm using constants for my error messages inside the Views, and I want to be able to use variables inside them for easier management.
Most of my constants looks like this:
const SUCCESSFULLY_REGISTERED = "<p class='success'>Registration successful!.</p>";
What I want to do is to use a variable for the css class, so that it's easier to change them all in one place. This is what I've tried:
const SUCCESSFULLY_REGISTERED = "<p class='$this->cssClassSuccess'>Registration successful!.</p><p>Log in with the username and password you registered with.</p>";
By some reason that doesn't work and raises the error message below. Why is that and how can this be done in a way that works?
Parse error: syntax error, unexpected '"' in .../View/RegisterView.php on line 15
This is not possible if you define a constant.
Manual: "The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation,
or a function call."
Constant Manual php.net
Constant Expression
This won't work because constants (as the name implies) need to be constant, but you can work around it with printf().
Example:
const SUCCESSFULLY_REGISTERED = '<p class="%s">Registration successful blah blah blah!</p>'
And then in your view script:
printf(SUCCESSFULLY_REGISTERED, $this->cssClassSuccess);
The %s in the constant will be replaced with the value of $this->cssClassSuccess
Manual: As of PHP 5.3.0, it's possible to reference the class using a variable.
Check the following class below:
<?php
class A{
function __construct($v)
{
define("MyConstant",$v);
echo "MyConstant is ". MyConstant;
}
}
$a = new A("hello"); //will print MyConstant is hello
?>
In the code above we are assigning the value of a variable ($v) to constant MyConstant. It will not give an error and the result of running this function will be MyConstant is hello
However, suppose you added a new line like so:
$a = new A("hello"); //will print MyConstant is hello
$b = new A("New Value"); //will generate Constant MyConstant already defined notice..
Here the line $b = new A("New Value"); will throw a notice stating: Notice: Constant MyConstant already defined. This is because constants defined within a class are pseudo-class-constants, similar to being static variables in terms of the context to which the scope is bound. And since constants cannot be changed, and their scope is bound to the class, calling the error line above is essentially trying to "redefine" the constant, which as you know will result in the aforementioned error.
Having said that remember that if you use define to create a constant inside a class it is not a pure class constant - you cannot call it as A::MyConstant. At the same time if you had done const AnotherConstant = "Hey"; in Class A you can call it as A::AnotherConstant. However when using const to create a constant you cannot set its value to a variable.
I hope this gives a better clarity on how dynamic variables can and cannot be assigned to a constant.
The only way that you can dynamically generate a constant is using the define function like below. But as another answer pointed out, this won't be a class level constant.
define('SUCCESSFULLY_REGISTERED', "<p class='$this->cssClassSuccess'>Registration successful!.</p><p>Log in with the username and password you registered with.</p>");
The constant from that point forward can be referred to with SUCCESSFULL_REGISTERED and will be immutable.
Problem: Cast custom messages and pass variables for easier management
Solution: use a Decorator pattern
interface HtmlElementInterface {
public function getText();
public function render();
}
class DivDecorator implements HtmlElementInterface {
protected $innerHtml;
protected $class;
public function __construct($class = null, $innerHtml = null) {
$this->innerHtml = $innerHtml;
$this->class = $class;
}
public function getText() {
return $this->text;
}
public function render() {
return "<div class='{$this->class}'>" . $this->innerHtml . "</div>";
}
}
$message = "Error in the app";
$div = new DivDecorator("myclass", $message);
echo $div->render();

accessing static methods using a variable class name (PHP)

I am trying to access a static method, but using a variable as the class name. Is this possible? I seem to be having issues with it. I want to be able to do something like this:
class foo {
public static function bar() {
echo 'test';
}
}
$variable_class_name = 'foo';
$variable_class_name::bar();
And I want to be able to do similar using static variables as well.
That syntax is only supported in PHP 5.3 and later. Previous versions don't understand that syntax, hence your parse error (T_PAAMAYIM_NEKUDOTAYIM refers to the :: operator).
In previous versions you can try call_user_func(), passing it an array containing the class name and its method name:
$variable_class_name = 'foo';
call_user_func(array($variable_class_name, 'bar'));
You can use reflection for PHP 5.1 and above:
class foo {
public static $bar = 'foobar';
}
$class = 'foo';
$reflector = new ReflectionClass($class);
echo $reflector->getStaticPropertyValue('bar');
> foobar

How do I access static member of a class?

I am trying to access static member of a class.
my class is:
class A
{
public static $strName = 'A is my name'
public function xyz()
{
..
}
..
}
//Since I have bunch of classes stored in an array
$x = array('A');
echo $x::$strName;
I am getting error while printing. How can I print 'A is my name'
If A is a class, you can access it directly via A::$strName.
class A {
public static $strName = 'A is my name';
}
echo A::$strName; // outputs "A is my name"
Update:
Depending on what you have inside your array, whether its what I like to define as class objects or class literals could be a factor. I distinguish these two terms by,
$objClasses = array(new A(), new B()); // class objects
$myClasses = array('A','B'); // class literals
If you go the class literals approach, then using a foreach loop with PHP5.2.8 I am given a syntax error when using the scope resolution operator.
foreach ($myClasses as $class) {
echo $class::$strName;
//syntax error, unexpected '::', expecting ',' or ';'
}
So then I thought about using the class objects approach, but the only way I could actually output the static variable was with an instance of an object and using the self keyword like so,
class A {
public static $strName = 'A is my name';
function getStatic() {
return self::$strName;
}
}
class B {
public static $strName = 'B is my name';
function getStatic() {
return self::$strName;
}
}
And then invoke that method when iterating,
foreach($objClasses as $obj) {
echo $obj->getStatic();
}
Which at that point why declare the variable static at all? It defeats the whole idea of accessing a variable without the need to instantiate an object.
In short, once we have more information as to what you would like to do, we can then go on and provide better answers.
If you want a working version for PHP5.2, you can use reflection to access the static property of a class.
class A {
static $strName= '123';
}
$lstClass = array('A');
foreach ($lstClass as $value) {
$c = new ReflectionClass($value);
echo $c->getStaticPropertyValue('strName');
}
Demo : http://ideone.com/HFJCW
You have a syntax error with missing semicolon and because it is an array you need to access the index of 0, or else it would be trying to call class 'Array'.
class A
{
public static $strName = 'A is my name';
public function xyz()
{
// left blank and removed syntax error
}
}
$x = array('A');
echo $x[0]::$strName;
Should fix it.
UPDATE
If you want to iterate over an array to call a class variable:
$x = array('A', 'B');
foreach ($x as $class) {
echo $class::$strName;
}
Not sure why you would want that, but there you go. And this has been tested, no errors were thrown, valid response of A is my name was received.
EDIT
Apparently this only works under PHP 5.3
I do find next one simple solution but don't know whether its good one or not.
My soln is:
eval('return '.$x[0].'::$strName;');
From inside a class and want to access a static data member of its own you can also use
static::
instead of
self::

PHP string to object name

Ok I have a string...
$a_string = "Product";
and I want to use this string in a call to a object like this:
$this->$a_string->some_function();
How the dickens do I dynamically call that object?
(don't think Im on php 5 mind)
So you the code you want to use would be:
$a_string = "Product";
$this->$a_string->some_function();
This code implies a few things. A class called Product with the method some_function(). $this has special meaning, and is only valid inside a class definition. So another class would have a member of Product class.
So to make your code legal, here's the code.
class Product {
public function some_function() {
print "I just printed Product->some_function()!";
}
}
class AnotherClass {
public $Product;
function __construct() {
$this->Product = new Product();
}
public function callSomeCode() {
// Here's your code!
$a_string = "Product";
$this->$a_string->some_function();
}
}
Then you can call it with this:
$MyInstanceOfAnotherClass = new AnotherClass();
$MyInstanceOfAnotherClass->callSomeCode();
I seem to have read this question differently from everyone else who's responded, but are you trying to use variable variables?
In the code you've shown, it looks like you're trying to call a function from string itself. My guess is that you want to call a function from a class with the same name as that string, in this case "Product."
This is what that would look like:
$this->Product->some_function();
It seems you might instead be looking for something like this:
$Product = new Product();
$Product->some_function();
EDIT: You need to be running PHP5 in order to do any method chaining. After that, what you have is perfectly legal.
Let's see if I got your intentions correctly...
$some_obj=$this->$a_string;
$some_obj->some_function();
So you've got an object, and one of it's properties (called "Product") is another object which has a method called some_function().
This works for me (in PHP5.3):
<?PHP
class Foo {
var $bar;
}
class Bar {
function some_func(){
echo "hello!\n";
}
}
$f = new Foo();
$f->bar = new Bar();
$str = 'bar';
$f->$str->some_func(); //echos "hello!"
I don't have PHP4 around, but if it doesn't work there, you might need to use call_user_func() (or call_user_func_array() if you need to pass arguments to some_function()

Categories