PHP: Why am I getting "Undefined property: myCar::$model" - php

I'm new to PHP and I am trying to follow a course.
<?php
class myCar {
function myCar() {
$this->model = "Sports";
}
}
$Range_Rover = new myCar();
echo $Range_Rover->model;
?>
According to the tutorial I should get the output "Sports" What is causing the code to result in an error of undefined property?
Warning: Undefined property: myCar::$model in
C:\xampp\htdocs\Test\index.php on line 16
Screenshot of tutorial results
Many thanks,
Stuart

Correct way to do it:
<?php
class myCar {
public $model;
function __construct() {
$this->model = "Sports";
}
}
$Range_Rover = new myCar();
echo $Range_Rover->model;
Output: https://3v4l.org/bnNrm
Note: Why above is needed
a) Defining constructor name as class name is an older practice, and it will give you deprecation message for some php version (php 7 versions).
b) Also from php8 it will be treated like a normal function, not as a constructor, so your purpose will not solve.

You need to declare the class variable before using it.
Just add "public $model;" before function mycar().

You should declare model like this
public $model;
Also as some answers told before, the constructor needs to be defined as __constructor now. this would look like
<?php
class myCar {
public $model;
function __constructor() {
$this->model = "Sports";
}
}
$Range_Rover = new myCar();
echo $Range_Rover->model;
?>

Related

Passing an instance of a Class with methods to a function PHP

I am struggling with some PHP code here. Like the title says, I am trying to pass an instance of a Class as a parameter to a function (Note, this file is in another file and has a different scope, and thus I need to pass it as a parameter).
This is the code I have currently set up:
// requires built this page, the classes and the functions are in seperate files.
// That's why I need to pass it in as a parameter.
class ClassName {
private $name;
private $age;
public function getAge(){
return $this->age;
}
} $className = new ClassName();
// seperate file
var_dump($className); // works, but has no methods.
function randomFunc($className){
echo $className->getAge(); // call to undefined method className::getAge()
} randomFunc($className);
EDIT 2:
I have uploaded my code here:
http://sandbox.onlinephpfunctions.com/code/99954d61ca4d3f53ce549dab9f8333630633d89c
I hope you people can help me, any help would be much appreciated.
This works fine:
<?php
class ClassName {
private $name;
private $age = 19;
public function getAge(){
return $this->age;
}
}
function randomFunc($className){
echo $className->getAge(); // call to undefined method className::getAge()
}
$className = new ClassName();
randomFunc($className);
Outputs: 19
Your code also runs fine for me, it just outputs nothing since $age is empty.
What version of PHP are you running?

Call static method of variable class from anothers class property in PHP

I want to call a static method from a variabe class in PHP. As pointed out several times on SO and because it is general practice, the following works as expected:
class Foo {
public function compile($strClass) {
$strClass::find(); // this works
}
}
Nonetheless I have to call different find methods from $strClass from different methods of a class Foo. That is, why I want to store $strClass in $this->strClass. Unfortunately, this doesn't work:
class Foo {
protected $strClass;
public function __construct($strClass)
{
$this->strClass = $strClass;
}
public function compile($strClass) {
$this->strClass::find(); // this does not work
}
}
Any idea or hint on how to solve that issue?
Update:
As pointed out in the comments, it might be a solution to use call_user_func like this:
call_user_func(array($this->strClass, 'find'), $strParam);
Anyhow, this makes code completion in PHPstorm impossible. Any hints on that? Maybe using code annotation?
You can change your compile method to this:
public function compile($strClass) {
call_user_func(array($this->strClass, 'find'));
}
This class design is flawed. I would try to get rid of the static methods completely, but here is a solution that exploits the fact that you can call static methods on objects:
class Foo {
protected $strClass;
public function __construct($strClass)
{
$this->strClass = new $strClass;
}
public function compile($strClass) {
$this->strClass::find();
}
}
UPDATE: nevermind, this is a syntax error in all current PHP versions, you actually have to do it like this:
$strClass = $this->strClass;
$strClass::find();
And this works with your original code as well, where $this->strClass is a string.

Pass the current class as parameter

I have a class like this:
// file /models/person.php
class Person
{
public function create_path()
{
self::log();
path_helper($this); //a global function in other php file
}
public function log()
{
echo "trying to create a path";
}
}
This is the way how Person is instanciated:
//file /tools/Builder.php
include('/models/Person.php');
class Builder
{
public function build()
{
$type = 'Person';
$temp = new $type();
$temp->create_path();
}
}
As you note in Person class, I am calling the object in question with $this reference. But this is not correct because an error is showed:
Message: Undefined variable: this
I suppose that $this reference point to other object or it is unable to work because the object is created from another script. Also, I tried to use self because there was not problem calling methods with that, but as parameter I get:
Message: Use of undefined constant self - assumed 'self'
So, can you guide me to the right direction?
I tested your code out for myself, with a few minor changes. It appears to work properly.
Changed self::log() to $this->log()
Added global function path_helper (I have no idea what this does)
PHP
function path_helper(Person $object)
{
var_dump($object);
}
class Person
{
public function create_path()
{
$this->log();
path_helper($this); //a global function in other php file
}
public function log()
{
echo "trying to create a path";
}
}
class Builder
{
public function build()
{
$type = 'Person';
$temp = new $type();
$temp->create_path();
}
}
$Build = new Builder();
$Build->build();
Result
trying to create a path
object(Person)[2]
Your code is correct and your going in the right direction.
You should call the log method like this:
$this->log();
because using self:: is reserved for static methods.
Also, try calling the path_helper function like this:
path_helper(self);
Hope I could help you. Couldn't test it, but it should work.

Undefined class constant 'self::STRING'

I've been struggling for a few days now with a completely weird bug:
Here's the scenario (bear with me):
I have one "framework" class, which I'll call F.
I have some simple classes that extend F, one of them I'll call P.
So what I have is:
class F {
[...]
protected static $_tabela;
[...]
final public static function _Tabela() {
return static::$_tabela;
}
public static function Consultar() {
echo static::_Tabela();
}
}
class P extends F {
protected static $_tabela = 'produtos';
}
And when I call P::Consultar(); I get this error that makes no sense to me:
Fatal error: Undefined class constant 'self::STRING' in [...]/F.inc.php on line X
Where X is the body of the _Tabela() method.
So, I've tried changing the variable name ($_tabela).
I tried saving the class name via get_called_class():
$class = get_called_class()
return $class::$_tabela;
But got the same error.
Also, the error message is completely useless, I'm not trying to access a class constant, but instead a class static property!
Googling the error message also gave me no useful results.
Edit: Thanks everyone for the answers!
I found the problem, and it had nothing to do with the code I was looking at.
Turns out there was an error in the definition of the P class, so when I tried calling static::Consultar, PHP parsed the class and complained about the error!
If you're using PHP version >= 5.3.0 , you can do this:
<?php
class F {
protected static $_tabela = 'a';
final public static function _Tabela() {
$s = new static();
return $s::$_tabela;
}
public static function Consultar() {
$s = new static();
echo $s::_Tabela();
}
}
class P extends F {
protected static $_tabela = 'produtos';
}
echo P::Consultar(); // echos 'produtos'

Accessing class constants from instance stored in another class

I have a class defined which has several constants defined through `const FIRST = 'something';
I have instantiated the class as $class = new MyClass()
then I have another class that takes a MyClass instance as one of it's constructors parameters and stores it as $this->model = $myClassInstance;
This works fine.
But I am wondering how I can access the constants from that instance?
I tried case $this->model::STATE_PROCESSING but my IDE tells me
Incorrect access to static class member.
and PHP tells me
unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM) in ...
I know I can do MyClass::STATE_PROCESSING but I am wondering if there is a way to get them based off the instance?
Seems like your on an older version of php? PHP 5.3 allows the access of constants in the manner you describe... However, this is how you can do it without that inherent ability:
class ThisClass
{
const FIRST = 'hey';
public function getFIRST()
{
return self::FIRST;
}
}
class ThatClass
{
private $model;
public function setModel(ThisClass $model)
{
$this->model = $model;
}
public function getModel()
{
return $this->model;
}
public function Hailwood()
{
$test = $this->model;
return $test::FIRST;
}
}
$ThisObject = new ThisClass();
echo $ThisObject ->getFIRST(); //returns: hey
echo $ThisObject ::FIRST; //returns: hey; PHP >= 5.3
// Edit: Based on OP's comments
$ThatObject= new ThatClass();
$ThatObject->setModel($Class);
echo $ThatObject->getModel()->getFIRST(); //returns: hey
echo $ThatObject->Hailwood(); //returns: hey
Basically, were creating a 'getter' function to access the constant. The same way you would to externally access private variables.
See the OOP Class Constants Docs: http://php.net/manual/en/language.oop5.constants.php

Categories