This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reference - What does this symbol mean in PHP?
So I've been reading through the book PHP Solutions, Dynamic Web Design Made Easy by David Powers. I read through the short section on Object Oriented PHP, and I am having a hard time grasping the idea of the -> operator. Can anyone try to give me a solid explanation on the -> operator in OOP PHP?
Example:
$westcost = new DateTimeZone('America/Los_Angeles');
$now->setTimezone($westcoast);
Also,a more general example:
$someObject->propertyName
The -> operator in PHP refers to either a function or a variable inside a class.
<?php
class Example {
public $variableInClass = "stringContent";
public function functionInClass() {
return "functionReturn";
}
}
$example = new Example();
var_dump($example->variableInClass); //stringContent
var_dump($example->functionInClass()); //functionReturn
?>
Do note that if we're talking about static classes (different purpose), you use :: instead:
<?php
class Example {
public static $variableInClass = "stringContent";
public static function functionInClass() {
return "functionReturn";
}
}
var_dump($example::$variableInClass); //stringContent
var_dump($example::functionInClass()); //functionReturn
?>
$someObject->propertyName can be read as:
return value stored in propertyName from object $someObject
$someObject->methodName() can be read as:
execute methodName from object $someObject
Classes and objects 101:
A class is defined as such:
class MyClass {
public $value1;
public function getValue() {
return $this->value;
}
}
We now defined a class with a single property, and a single function. To use these, we need to create an 'instance' of this object:
$myObject = new MyClass();
To use the property or function, we use the -> operator:
echo $myObject->value1;
echo $myObject->getValue();
Put a little bit more abstractly.. the function getValue is defined in this object. By using the -> operator on an instance of our class, what PHP does is effectively just call the function, just like any other function.. but before it gets called $this is assigned to the current object.
Hope this helps, if not.. I would simply recommend reading about OOP basics.
Related
What I would like to do after creating an instance of a class is to be able to call the name of that instance as a function. For example, consider the following class Foo:
$bar = new Foo(5); // generates 5 random ints between 0-100
bar(3); // get the third int in the object bar
Is this even possible in PHP or would it involve messing with the parser? Thanks in advance!
What this question is really about is creating a PHP functor and here's an example I lifted from here:
<?php
class SquareCallback
{
public function __invoke($value)
{
return $value * $value;
}
}
$squareObject = new SquareCallback;
var_dump($squareObject(3));
I'm developing a program that has to do with Question asking, so imagine there's the Question class. If I wanted to refer to a static function in Question which creates a Question item could I assign this object to $this variable?
In a more general perspective
Is it possible to change the value of $this variable of a class? If yes, how can you do that? Otherwise why can't I hook $this to another object of same class?
The pseudo-variable $this is a reference to the calling object. Trying to re-assign it will generate a fatal error.
PHP manual: http://php.net/manual/en/language.oop5.basic.php
Similar question: PHP Fatal error: Cannot re-assign $this
So, I think you are a little foggy on what $this is for. It is simply a way to refer to the instance of the class that is being utilized. This reference only occurs within the class.
For example:
class Question
{
function __construct($question, $correctAnswer)
{
$this->question = $question;
$this->correctAnswer = $correctAnswer;
}
function answerQuestion($answer)
{
if ($answer == $this->correctAnswer) {
return true;
} else {
return false;
}
}
}
Notice to determine if the answer is correct we compare the provided answer against:
$this->correctAnswer
If we create two different questions:
$questionOne = new Question("Who is the founder of Microsoft?", "Bill Gates");
$questionTwo = new Question("Who is the CEO of Apple, Inc?", "Tim Cook");
And provide the same answer, we get different results:
$isCorrect = $questionOne->answerQuestion("Tim Cook"); // FALSE
$isCorrect = $questionTwo->answerQuestion("Tim Cook"); // TRUE
This is because $this refers to the instance being used.
So, within the class, you use $this.
Outside the class, you use the object name. In this case: $questionOne or $questionTwo
I hope that helps clear things up.
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
So I'm refactoring my code to implement more OOP. I set up a class to hold page attributes.
class PageAtrributes
{
private $db_connection;
private $page_title;
public function __construct($db_connection)
{
$this->db_connection = $db_connection;
$this->page_title = '';
}
public function get_page_title()
{
return $this->page_title;
}
public function set_page_title($page_title)
{
$this->page_title = $page_title;
}
}
Later on I call the set_page_title() function like so
function page_properties($objPortal) {
$objPage->set_page_title($myrow['title']);
}
When I do I receive the error message:
Call to a member function set_page_title() on a non-object
So what am I missing?
It means that $objPage is not an instance of an object. Can we see the code you used to initialize the variable?
As you expect a specific object type, you can also make use of PHPs type-hinting featureDocs to get the error when your logic is violated:
function page_properties(PageAtrributes $objPortal) {
...
$objPage->set_page_title($myrow['title']);
}
This function will only accept PageAtrributes for the first parameter.
There's an easy way to produce this error:
$joe = null;
$joe->anything();
Will render the error:
Fatal error: Call to a member function anything() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/casMail/dao/server.php on line 23
It would be a lot better if PHP would just say,
Fatal error: Call from Joe is not defined because (a) joe is null or (b) joe does not define anything() in on line <##>.
Usually you have build your class so that $joe is not defined in the constructor or
Either $objPage is not an instance variable OR your are overwriting $objPage with something that is not an instance of class PageAttributes.
It could also mean that when you initialized your object, you may have re-used the object name in another part of your code. Therefore changing it's aspect from an object to a standard variable.
IE
$game = new game;
$game->doGameStuff($gameReturn);
foreach($gameArray as $game)
{
$game['STUFF']; // No longer an object and is now a standard variable pointer for $game.
}
$game->doGameStuff($gameReturn); // Wont work because $game is declared as a standard variable. You need to be careful when using common variable names and were they are declared in your code.
function page_properties($objPortal) {
$objPage->set_page_title($myrow['title']);
}
looks like different names of variables $objPortal vs $objPage
I recommend the accepted answer above. If you are in a pinch, however, you could declare the object as a global within the page_properties function.
$objPage = new PageAtrributes;
function page_properties() {
global $objPage;
$objPage->set_page_title($myrow['title']);
}
I realized that I wasn't passing $objPage into page_properties(). It works fine now.
you can use 'use' in function like bellow example
function page_properties($objPortal) use($objPage){
$objPage->set_page_title($myrow['title']);
}
I'm learned php as functional and procedure language. Right now try to start learn objective-oriented and got an important question.
I have code:
class car {
function set_car($model) {
$this->model = $model;
}
function check_model()
{
if($this->model == "Mercedes") echo "Good car";
}
}
$mycar = new car;
$mycar->set_car("Mercedes");
echo $mycar->check_model();
Why it does work without declaration of $model?
var $model; in the begin?
Because in php works "auto-declaration" for any variables?
I'm stuck
Every object in PHP can get members w/o declaring them:
$mycar = new car;
$mycar->model = "Mercedes";
echo $mycar->check_model(); # Good car
That's PHP's default behaviour. Those are public. See manual.
Yes, if it doesn't exist, PHP declares it on the fly for you.
It is more elegant to define it anyway, and when working with extends it's recommended, because you can get weird situations if your extends are gonna use the same varnames and also don't define it private, protected or public.
More info:
http://www.php.net/manual/en/language.oop5.visibility.php
PHP class members can be created at any time. In this way it will be treated as public variable. To declare a private variable you need to declare it.
Yes. But this way variables will be public. And declaration class variable as "var" is deprecated - use public, protected or private.
No, it's because $model is an argument of the function set_car. Arguments are not exactly variables, but placeholders (references) to the variables or values that will be set when calling the function (or class method). E.g., $model takes the value "Mercedes" when calling set_car.
I think this behavior can lead to errors.
Lets consider this code with one misprint
declare(strict_types=1);
class A
{
public float $sum;
public function calcSum(float $a, float $b): float
{
$this->sum = $a;
$this->sums = $a + $b; //misprinted sums instead of sum
return $this->sum;
}
}
echo (new A())->calcSum(1, 1); //prints 1
Even I use PHP 7.4+ type hints and so one, neither compiler, nor IDE with code checkers can't find this typo.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calling closure assigned to object property directly
Why this is not possible in PHP? I want to be able to create a function on the fly for a particular object.
$a = 'a';
$tokenMapper->tokenJoinHistories = function($a) {
echo $a;
};
$tokenMapper->tokenJoinHistories($a);
PHP tries to match an instance method called "tokenJoinHistories" that is not defined in the original class
You have to do instead
$anon_func = $tokenMapper->tokenJoinHistories;
$anon_func($a);
Read the documentation here especially the comment part.
With $obj->foo() you call methods, but you want to call a property as a function/method. This just confuses the parser, because he didn't find a method with the name foo(), but he cannot expect any property to be something callable.
call_user_func($tokenMapper->tokenJoinHistories, $a);
Or you extend your mapper like
class Bar {
public function __call ($name, $args) {
if (isset($this->$name) && is_callable($this->$name)) {
return call_user_func_array($this->$name, $args);
} else {
throw new Exception("Undefined method '$name'");
}
}
}
(There are probably some issues within this quickly written example)