Reputation: 2012
I have 2 files index.php and class_lib.php.
Here is index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1" />
<title>OOP in PHP</title>
<?php include("class_lib.php"); ?>
</head>
<body>
<?php
$adrian = new person();
$jimmy = new person;
$adrian = set_name('adrian de cleir');
$jimmy = set_name('jimmy darmady');
echo $adrian->get_name();
?>
</body>
</html>
and the file with the class
<?php
class person {
var $name;
function set_name($new_name) {
$this->name = $new_name;
}
function get_name() {
return $this->name;
}
}
?>
When I load the page I get Fatal error: Call to undefined function set_name() in /var/www/php_learning_testing/index.php on line 15
Thanks for the help, its something silly im sure.
Upvotes: 0
Views: 2537
Reputation: 59
try to set public before the functions. Also replace var in to private. So far I know, var doesn't exist in php ;)
Upvotes: 0
Reputation: 2464
for jimmy you have $jimmy = new person; you should have
$jimmy = new person();
then to call a class method you do
$jimmy->set_name('bla');
Upvotes: 0
Reputation: 21979
set_name
doesn't exist in the global scope but only off the object, you're doing it right with get_name
.
$adrian = new person();
$jimmy = new person;
$adrian->set_name('adrian de cleir');
$jimmy->set_name('jimmy darmady');
echo $adrian->get_name();
Your existing code (should set_name
actually exist and return a value), would simply overwrite the objects person
with the return value of set_name
. Whenever you're calling non-static class methods, you always need to reference the instance.
Upvotes: 6
Reputation: 287835
In the lines
$adrian = set_name('adrian de cleir');
$jimmy = set_name('jimmy darmady');
you need to call the methods on the objects:
$adrian->set_name('adrian de cleir');
$jimmy->set_name('jimmy darmady');
Upvotes: 1