
<?php
##
## php 面向对象
## @石磊
class Like
{
## 属性
protected $username;
protected $foo = 'leave me';
protected $first = 'alone';
public function __construct(string $username = null)
{
$this->username = null !== $username ? $username : 'Please';
}
## 方法
public function test():int
{
printf('PHP:'. $this->username . ',' . $this->foo . ' ' . $this->first . '!');
return 0;
}
}
## 实例化
$foo = new Like('Stone');
## 客户端调用
$foo->test();
## 结果:PHP:Stone,leave me alone!
?>
<script>
//
// 构造方法创建JS对象(基于JS原型【prototype属性】,好处:方法共用一个内存)
// @石磊
var Like = function (props) {
// 验证非空
props = 'undefined' === typeof(props) ? {} : props;
// 属性(props是一个对象,当然如果是json对象会更好)
this.username = 'username' in props ? props.username : 'Please';
this.foo = 'leave me';
this.first = 'alone';
// 方法(基于原型的方法,不可用this)
Like.prototype.test = function(){
console.log('JS:' + this.username + ',' + this.foo + ' ' + this.first+ '!');
return 0;
}
}
///////////////////////////// 实例化调用 ///////////////////////////
// 实例化
var foo = new Like({username:'Sweet'});
// 客户端调用
foo.test();
// 结果:JS:Sweet,leave me alone!
</script>
文章来源: js对象与php比较 - 笔记搬迁7
人吐槽 | 人点赞 |
发表评论