Reputation: 193
Why can I not do something like the following when I know that the property of myobject
is going to be declared already:
define('title','boats');
myobject->title
;
but this works:
myobject->boats
Is this even good practice?
Upvotes: 0
Views: 76
Reputation: 18859
Why can I not do something like the following when I know that the property of myobject is going to be declared already:
Probably because PHP expects you to call it with a method name. There are options, though:
<?php
define( 'METHOD', 'bar' );
class Foo {
public function bar( ) {
echo "Foo->bar( ) called.\n";
}
}
$foo = new Foo;
call_user_func( array( $foo, METHOD ) );
// or
$method = METHOD;
$foo->$method( );
EDIT: Ah, I seem to have misunderstood. My version is for calling methods of which the name is defined in a constant, whereas you were looking for a way of calling properties. Well, I'll leave it in here for future reference anyway.
Upvotes: 1
Reputation: 164910
You can't use
$myobject->title
as this is attempting to access the title
property of your object. If this property does not exist, an error will be triggered.
You can use
$myobject->{title}
but I'd rather see you use a variable instead of a constant, eg
$title = 'boats';
echo $myobject->$title;
Ideally, you will know which property you want to access and use its name appropriately
$myobject->boats
Upvotes: 3